如何检查MongoDB中是否存在key

rslzwgfq  于 2023-04-18  发布在  Go
关注(0)|答案(3)|浏览(368)

我尝试检查MongoDB集合中是否存在一个键。基本上,我需要将一个字符串数组Map到一个特定的键。如果键存在,我希望通过添加新值来更新列表,否则创建一个具有初始值的新键(如果添加新键,则最初只添加1个值)。
我在网上找到了一些例子,虽然我还没有能够让它在本地工作。下面是我的代码(我使用的是官方的Go MongoDB驱动程序):

key:= "some_key"
database := client.Database("dbName")
keysCollection := database.Collection("keys")
keysCollection.Find(nil, {key:{$exists:true}});

关于此组件{key: {$exists:true}},我遇到了两个问题

  • invalid character U+0024 '$':当试图检查key是否存在时,在{$exists:true},尽管这似乎是MongoDB文档支持的检查键本身是否存在,而不检查Map到它的确切值
  • syntax error: unexpected {, expecting expression:在{key: {$exists:true}}的开头,看起来我不能传递结构体?

这是我第一次使用MongoDB,我对GoLang的经验很少,并且被这个看起来很小的问题卡住了。
我这样做对吗?如果是这样,我如何才能越过这些问题?

rt4zxlrg

rt4zxlrg1#

为了检查集合中是否存在键,以下是分别在mongo shell和 golang 中的查询。假设示例文档的集合为:

{ _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集合中是否存在一个键。我需要将一个字符串数组Map到一个特定的键。如果该键存在,我希望通过添加新值来更新列表,否则创建一个具有初始值的新键(如果添加新键,则最初只会添加1个值)。
要根据条件更新字段,您需要使用Update With Aggregation Pipeline。以下shell和 golang 查询将使用条件更新所有文档-如果数组字段存在,则添加来自newValue的值 * 或 * 如果字段不存在,则使用来自newValue的值创建新字段arr

var newValue = "white"

db.collection.updateMany(
  { },
  [ { 
       $set: { 
           arr: { 
               $concatArrays: [ 
                   { $ifNull: [ "$arr", [ ] ] }, 
                   [ newValue ] 
               ] 
           } 
       } 
  } ]
)
  • 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)
gwo2fgha

gwo2fgha2#

试试这个

var res []MyType
err := keysCollection.Find(ctx, bson.M{key: bson.M{"$exists": true}}, &res)
46scxncf

46scxncf3#

使用下面的查询,我们将得到所有结果。

db.getCollection('botConfig').find({"Keyval":{'$exists': 1}})
or 
db.getCollection('botConfig').find({"handoffSettings":{'$exists': true}})

请检查文档以获取更多信息。

相关问题