go mongo-driver 模糊查找语法
模糊查询($regex)
findOptions := options.Find()
findfilter := bson.M{"name":bson.M{"$regex":"Mi","$options": "$i"}}
cur,err := collection.Find(context.TODO(),findfilter,findOptions)
$regex"表示字符串匹配,"$options": "$i"表示不区分大小写
findfilter := bson.M{ "name":bson.M{"$regex":"^[0-9]+"}}
普通运算符语法
- 等于 ($eq)
findfilter := bson.M{
"name":bson.M{"$eq":"misty"},
"age":bson.M{"$eq": 15}, }
- 不等于($ne)
findfilter := bson.M{
"name":bson.M{"$ne":"misty"},
"age":bson.M{"$eq": 15}, }
- 大于($gt)
findfilter := bson.M{
"name":bson.M{"$ne":"misty"},
"age":bson.M{"$gt": 15}, }
- 大于等于($gte)
findfilter := bson.M{
"name":bson.M{"$ne":"misty"},
"age":bson.M{"$gte": 15}, }
- 小于($lt)
findfilter := bson.M{
"name":bson.M{"$ne":"misty"},
"age":bson.M{"$lt": 15}, }
- 小于等于($lte)
findfilter := bson.M{
"name":bson.M{"$ne":"misty"},
"age":bson.M{"$lte": 15}, }
in 、 no in
- in($in)
findfilter := bson.M{"name":bson.M{"$in": []string{"Brock","Ash"}}}
- no in($nin)
findfilter := bson.M{"name":bson.M{"$nin": []string{"Brock","Ash"}}}
是否包含($exists)
findfilter := bson.M{"name":bson.M{"$exists": true}}
查询键值为null的字段
findfilter := bson.M{"name":bson.M{"$in":[]interface{}{null}, "$exists": true}}
$size
查询键值为长度是size的数组
//查询Interests数组长度为3的所有人
findfilter := bson.M{"Interests": bson.M{"$size": 3}}
$all
查询数组中包含所有值得匹配(不分顺序,只看包含与否)
//查询Interests中包含11,22,33的所有人
findfilter := bson.M{"Interests": bson.M{"$all": []string{"11","22","33"}}}
如果数组只有一项内容
bson.M{"Interests": bson.M{"$all": []string{"11"}}}
bson.M{"Interests": "11"}
以上结果一致
多条件查询
- 与 ($and)
findfilter := bson.M{ "name": "jimmy","age":33}
- 或 ($or)
findfilter := bson.M{"$or": []bson.M{bson.M{"name": "Jimmy Kuu"}, bson.M{"age": 31}}}
更新 ($set)
//更新
filter := bson.M{
"_id": bson.M{"$in": bson.A{results[0].Id,results[1].Id}},
}
//update := bson.D{
// {"$inc",bson.D{
// {"age",100},
// },},
//}
update := bson.M{
"$set": bson.M{
"age" : 100,
"name" :"测修100",
},
}
updateResult,err := collection.UpdateMany(context.TODO(),filter,update)
字段增加值 ($inc)
temp,_:= primitive.ObjectIDFromHex("5e576f5a05aa6eee357b7b2a")
filter = bson.M{"_id": temp}
update = bson.M{"$inc": bson.M{ "age": 2}}
updateResult,err := collection.UpdateMany(context.TODO(),filter,update)
从数组中增加一个元素($push)
temp,_:= primitive.ObjectIDFromHex("5e576f5a05aa6eee357b7b2a")
filter = bson.M{"_id": temp}
update = bson.M{"$push": bson.M{ "interests": "Golang", }}
updateResult,err := collection.UpdateMany(context.TODO(),filter,update)
从数组中删除一个元素($pull)
temp,_:= primitive.ObjectIDFromHex("5e576f5a05aa6eee357b7b2a")
filter = bson.M{"_id": temp}
update = bson.M{"$pull": bson.M{ "interests": "Golang", }}
updateResult,err := collection.UpdateMany(context.TODO(),filter,update)