登录
首页 >  Golang >  Go问答

检查 MongoDB 中是否存在密钥的方法

来源:stackoverflow

时间:2024-03-07 17:09:25 310浏览 收藏

一分耕耘,一分收获!既然都打开这篇《检查 MongoDB 中是否存在密钥的方法》,就坚持看下去,学下去吧!本文主要会给大家讲到等等知识点,如果大家对本文有好的建议或者看到有不足之处,非常欢迎大家积极提出!在后续文章我会继续更新Golang相关的内容,希望对大家都有所帮助!

问题内容

我正在尝试检查 mongodb 集合中是否存在某个键。基本上,我需要将字符串数组映射到特定的键。如果该键存在,我想通过添加新值来更新列表,否则创建一个具有初始值的新键(如果添加新键,则最初只会添加 1 个值)。

我在网上找到了一些示例,尽管我无法让它在本地工作。下面是我的代码(我使用官方 go mongodb 驱动程序):

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

我在这个组件 {key: {$exists:true}}{key: {$exists:true}}

  • invalid character u+0024 '$':当尝试检查 key 是否存在时,在 {$exists:true} 处,尽管这似乎是 mongodb 文档支持检查密钥本身是否存在的内容,而不检查映射到它的确切值
  • 语法错误:意外{,期望表达式:在{key:{$exists:true}}的开头,看起来我无法传递结构?

这是我第一次使用 mongodb,我对 golang 的经验很少,并且被这个看似小问题困扰。

我的处理方式正确吗?如果是这样,我该如何克服这些问题?


正确答案


要检查集合中是否存在某个键,以下分别是 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 集合中是否存在某个键。我需要 将字符串数组映射到特定键。如果密钥存在,我 想要通过添加新值来更新列表,否则创建一个新值 具有初始值的密钥(如果添加新密钥,则只会 最初添加了 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)

试试这个

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

终于介绍完啦!小伙伴们,这篇关于《检查 MongoDB 中是否存在密钥的方法》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>