Codementor Events

Update Arrays in MongoDb

Published Mar 23, 2017
Update Arrays in MongoDb

Sometimes, when you're using MongoDb, you might end up with a document structure like the one below. And like me, sometime ago, you might wonder how you can update data in a particular array's child object without knowing the exact position of the child.

For example: If you want to update the answer to the question: "For how long has the www existed " in the "questions" array below, without prior knowledge of its position in the "questions" array.

// db.questions
{
  "_id" : "3qai330dkqwxd9sw",
  "sections" : {
        title: "JHS",
        questions: [{
            question: "How soon can I visit my Family",
            answer: "that's a prayer point"
            },
            {
            question: "How do I get started with mongoDb",
            answer: "visit www.mongodb.org and attend their online university"
            },
            {
            question: "For how long has the www existed",
            answer: "1 day"
            },
            {
            question: "Is there any solution out there that isnt algorithmic"
            answer: "ask the baberians"
                    }]
      }
}

Fortunately, this is super-easy !

    db.questions.update(
      {
        "_id" : "3qai330dkqwxd9sw",
        "section.questions.question" : "For how long has the www existed"
      },
      {
        "$set" :
        {
            "sections.questions.$.answer": "10231 days old plus daysAfterThisPost"
        }
      }
    );

Voila!

Did you notice the $ sign? It does the magic!

What Happens is:

  1. "section.questions.question" : "For how long has the www existed" tells mongo to search the "sections.questions" array for the child that has the question: "For how long has the www existed "
  2. then "sections.questions.$.answer": "10231 days old + Today - dateOfThisPost" tells mongo to update the answer to the question found above

Note that when specifying the field, "section.questions.question", I do not need to know/include the position of the question in the array like this "section.questions.2.question"

I hope you found this post helpful!

Discover and read more posts from Uyiosa Enabulele
get started
post commentsBe the first to share your opinion
SHIVA GUPTA
5 years ago

say if you have an array which has three properties
version
name
url
now if i want to update all with same version with different values
i.e i want to select array elements on the basis of version but i have three different update values for url

Damir Ljubičić
6 years ago

Thank you so much for this post. Finally solved this problem after week of trying

Show more replies