'How to check if key exists in MongoDB
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 thekeyexists, 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 itsyntax 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?
Solution 1:[1]
Try this
var res []MyType
err := keysCollection.Find(ctx, bson.M{key: bson.M{"$exists": true}}, &res)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
