How to check if key exists in MongoDB

Issue

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?

Solution

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: [ "red", "blue" ] }
{ _id: 2  }

The query:

db.collection.find( { "arr": { "$exists": true } } )

See the usage of $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)


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 = "white"

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

The golang update:

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)

Answered By – prasad_

Answer Checked By – Candace Johnson (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.