如何在MongoDB中检查键是否存在

huangapple go评论88阅读模式
英文:

How to check if key exists in MongoDB

问题

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

我在网上找到了一些示例,但是我无法在本地使其工作。以下是我的代码(我正在使用官方的 Go MongoDB 驱动程序):

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

我在这个组件 {key: {$exists:true}} 遇到了两个问题:

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

这是我第一次使用 MongoDB,并且我在 GoLang 方面经验很少,我在这个看似小问题上卡住了。

我这样做的方式正确吗?如果是的话,我该如何解决这些问题?

英文:

I am trying to check if a key exists in a MongoDB collection. Basically, I need to map an array of strings to a specific key. If the key exists, I want to update the list by adding a new value, otherwise create a new key with an initial value (If a new key is added, it will only be added with 1 value initially).

I have found some examples online, though I haven't been able to get it to work locally. Here is my code below (I am using the official Go MongoDB driver):

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

I'm running into 2 issues around this component {key: {$exists:true}}

  • invalid character U+0024 '$': when trying to check if the key exists, at {$exists:true}, though this seems to be what the MongoDB documentation supports to check if the key itself exists, without checking for an exact value mapped to it
  • syntax error: unexpected {, expecting expression: at the beginning of {key: {$exists:true}}, it looks like I cannot pass a struct?

This is my first time working with MongoDB, and I have very little experience in GoLang, and am stuck on this seeming small issue.

Am I going about this the right way? If so, how can I move past these issues?

答案1

得分: 8

要检查一个键是否存在于集合中,可以使用以下在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("找到一个文档:%+v\n", result)

<br>

<hr>

> 我正在尝试检查一个键是否存在于MongoDB集合中。我需要将一个字符串数组映射到一个特定的键。如果键存在,我希望通过添加一个新值来更新列表,否则创建一个具有初始值的新键(如果添加了一个新键,它将只有一个初始值)。

要根据条件更新字段,需要使用带有聚合管道的更新。以下是在shell和_golang_中更新满足条件的所有文档的查询 - 如果数组字段存在,则将newValue的值添加到arr中,如果字段不存在,则创建一个名为arr的新字段,并将newValue的值赋给它。

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("匹配了%v个文档并更新了%v个文档。\n", updateResult.MatchedCount, updateResult.ModifiedCount)
英文:

To check if a key exists in a collection the following are the queries in mongo shell and golang respectively. Assume a collection of sample documents as:

{ _id: 1, arr: [ &quot;red&quot;, &quot;blue&quot; ] }
{ _id: 2  }

The query:

db.collection.find( { &quot;arr&quot;: { &quot;$exists&quot;: true } } )

See the usage of $exists.

var result bson.M
filter := bson.D{{ &quot;arr&quot;, bson.D{{ &quot;$exists&quot;, true }} }}
err = collection.FindOne(context.TODO(), filter).Decode(&amp;result)
if err != nil {
    log.Fatal(err)
}
fmt.Printf(&quot;Found a single document: %+v\n&quot;, result)

<br>

<hr>

> I am trying to check if a key exists in a MongoDB collection. I need
> to map an array of strings to a specific key. If the key exists, I
> want to update the list by adding a new value, otherwise create a new
> key with an initial value (If a new key is added, it will only be
> added with 1 value initially).

To update a field based upon a condition, you need to use an Update With Aggregation Pipeline. The following shell and golang queries update all documents with the condition - if the array field exists, it adds the value from newValue or if the field doesn''t exist, creates a new field arr with the value fromnewValue.

var newValue = &quot;white&quot;

db.collection.updateMany(
  { },
  [ { 
       $set: { 
           arr: { 
               $concatArrays: [ 
                   { $ifNull: [ &quot;$arr&quot;, [ ] ] }, 
                   [ newValue ] 
               ] 
           } 
       } 
  } ]
)

The golang update:

newValue := &quot;white&quot;
filter := bson.D{{}}

pipe := bson.D{{ &quot;$set&quot;, bson.D{{ &quot;arr&quot;, bson.D{{ &quot;$concatArrays&quot;, bson.A{ bson.D{{&quot;$ifNull&quot;,bson.A{ &quot;$arr&quot;, bson.A{} }}}, bson.A{ newValue } } }} }} }}
	
updateResult, errr := collection.UpdateMany(ctx, filter, mongo.Pipeline{ pipe })
	
if errr != nil {
    log.Fatal(errr)
}
fmt.Printf(&quot;Matched %v documents and updated %v documents.\n&quot;, updateResult.MatchedCount, updateResult.ModifiedCount)

答案2

得分: 0

尝试这样做:

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

Try this

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

答案3

得分: 0

使用以下查询,我们将获得所有结果。

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

请查看文档获取更多信息:链接

英文:

use the below query, we will get all results.

db.getCollection(&#39;botConfig&#39;).find({&quot;Keyval&quot;:{&#39;$exists&#39;: 1}})
or 
db.getCollection(&#39;botConfig&#39;).find({&quot;handoffSettings&quot;:{&#39;$exists&#39;: true}})

please check the docs for more information.

huangapple
  • 本文由 发表于 2021年6月29日 00:36:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/68167039.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定