2 回答

TA貢獻1818條經驗 獲得超3個贊
要檢查集合中是否存在鍵,下面分別是 shell 和 golang 中的查詢。假設示例文檔的集合為:mongo
{ _id: 1, arr: [ "red", "blue" ] }
{ _id: 2 }
查詢:
db.collection.find( { "arr": { "$exists": true } } )
請參閱$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個值)。
若要根據條件更新字段,需要使用聚合管道進行更新。以下 shell 和 golang 查詢使用條件更新所有文檔 - 如果數組字段存在,則添加來自 的值,或者如果該字段不存在,則使用來自的值創建一個新字段。newValuearrnewValue
var newValue = "white"
db.collection.updateMany(
{ },
[ {
$set: {
arr: {
$concatArrays: [
{ $ifNull: [ "$arr", [ ] ] },
[ newValue ]
]
}
}
} ]
)
戈朗更新:
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)

TA貢獻1876條經驗 獲得超5個贊
試試這個
var res []MyType err := keysCollection.Find(ctx, bson.M{key: bson.M{"$exists": true}}, &res)
- 2 回答
- 0 關注
- 118 瀏覽
添加回答
舉報