我正在尝试检查 MongoDB 集合中是否存在某个键。基本上,我需要将字符串数组映射到特定的键。如果该键存在,我想通过添加新值来更新列表,否则创建一个具有初始值的新键(如果添加新键,则最初只会添加 1 个值)。
我在网上找到了一些例子,尽管我无法让它在本地工作。下面是我的代码(我使用的是官方 Go MongoDB 驱动程序):
key:= "some_key"
database := client.Database("dbName")
keysCollection := database.Collection("keys")
keysCollection.Find(nil, {key:{$exists:true}});
Run Code Online (Sandbox Code Playgroud)
我遇到了关于这个组件的两个问题{key: {$exists:true}}
invalid character U+0024 '$'
:当尝试检查是否key
存在时, at {$exists:true}
,尽管这似乎是 MongoDB 文档支持检查键本身是否存在,而不检查映射到它的确切值syntax error: unexpected {, expecting expression
: 在 的开头{key: {$exists:true}}
,看起来我无法传递结构?这是我第一次使用 MongoDB,我对 GoLang 的经验很少,并且被这个看似小问题困扰。
我以正确的方式处理这件事吗?如果是这样,我该如何克服这些问题?
要检查集合中是否存在某个键,以下分别是mongo
shell 和golang中的查询。假设样本文档的集合为:
{ _id: 1, arr: [ "red", "blue" ] }
{ _id: 2 }
Run Code Online (Sandbox Code Playgroud)
查询:
db.collection.find( { "arr": { "$exists": true } } )
Run Code Online (Sandbox Code Playgroud)
请参阅$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)
Run Code Online (Sandbox Code Playgroud)
我正在尝试检查 MongoDB 集合中是否存在某个键。我需要将字符串数组映射到特定键。如果该键存在,我想通过添加新值来更新列表,否则创建一个具有初始值的新键(如果添加新键,则最初只会添加 1 个值)。
要根据条件更新字段,您需要使用Update With Aggregation Pipeline。以下 shell 和golang查询使用条件更新所有文档 - 如果数组字段存在,则添加来自 的值,newValue
或者如果该字段不存在,则使用arr
来自 的值创建一个新字段newValue
。
var newValue = "white"
db.collection.updateMany(
{ },
[ {
$set: {
arr: {
$concatArrays: [
{ $ifNull: [ "$arr", [ ] ] },
[ newValue ]
]
}
}
} ]
)
Run Code Online (Sandbox Code Playgroud)
golang更新:
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)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
19783 次 |
最近记录: |