要检查集合中是否存在某个键,请执行以下查询mongo
壳和golang分别。假设样本文档的集合为:
{ _id: 1, arr: [ "red", "blue" ] }
{ _id: 2 }
查询:
db.collection.find( { "arr": { "$exists": true } } )
查看用法$exists https://docs.mongodb.com/manual/reference/operator/query/exists/.
var result bson.M
filter := bson.D{{ "arr", bson.D{{ "$exists", true }} }}
err = collection.FindOne(context.TODO(), filter).Decode(&result)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Found a single document: %+v\n", result)
我正在尝试检查 MongoDB 集合中是否存在某个键。我需要
将字符串数组映射到特定键。如果密钥存在,我
想要通过添加新值来更新列表,否则创建一个新值
具有初始值的密钥(如果添加新密钥,则只会
最初添加 1 值)。
要根据条件更新字段,您需要使用使用聚合管道进行更新 https://docs.mongodb.com/manual/tutorial/update-documents-with-aggregation-pipeline/。以下外壳和golang查询使用条件更新所有文档 - 如果数组字段存在,则会添加来自的值newValue
or如果该字段不存在,则创建一个新字段arr
的值来自newValue
.
var newValue = "white"
db.collection.updateMany(
{ },
[ {
$set: {
arr: {
$concatArrays: [
{ $ifNull: [ "$arr", [ ] ] },
[ newValue ]
]
}
}
} ]
)
The golang update:
newValue := "white"
filter := bson.D{{}}
pipe := bson.D{{ "$set", bson.D{{ "arr", bson.D{{ "$concatArrays", bson.A{ bson.D{{"$ifNull",bson.A{ "$arr", bson.A{} }}}, bson.A{ newValue } } }} }} }}
updateResult, errr := collection.UpdateMany(ctx, filter, mongo.Pipeline{ pipe })
if errr != nil {
log.Fatal(errr)
}
fmt.Printf("Matched %v documents and updated %v documents.\n", updateResult.MatchedCount, updateResult.ModifiedCount)