MongoDB: update dictionary in document

konse picture konse · Mar 25, 2015 · Viewed 14.3k times · Source

I have a MongoDB document that saves occurrences of some things in a dictionary:

{
  "id" : 1,
  "occurrences" : {
    "1" : 1,
    "2" : 5,
    "17" : 1,
    "35" : 4
  }
}

I now want to add or update some entries, for example add a "12:3" to the occurrences, or update the number of occurrences of "17" to 2, so let's say as an example I want to add {"12":3} and {"17":2} to this dictionary. It is driving me crazy because I simply can not get it to work. I could use arrays and all that, but I would really like to have it in this particular design. Any ideas on how to solve this? I tried so many different things with $set and $each and so on.

Answer

DanM picture DanM · Mar 25, 2015

from mongoDb website look at "Set Fields in Embedded Documents"

To specify a <field> in an embedded document or in an array, use dot notation.
For the document matching the criteria _id equal to 100, the following
operation updates the make field in the details document:


db.products.update(
{ _id: 100 },
{ $set: { "details.make": "zzz" } })

in your case

db.collection.update(
     {_id:ObjectId("1")},
     { $set: { "occurrences.12": "3", "occurrences.17": "2" }})