How do I add another value to a dictionary in MongoDB?

mongo-shell, mongodb, shell

Solution

The OP's question and example don't match. He actually wants to insert a field into an array within the document, which means that

db.posts.update({name: "Hello, world!" }, { $push: {comments: "First comment!"}});

works just fine.

However, if you want to add a value or subdocument to a dictionary, you would use the `$set` command. Take this document as our example:

{
    "_id": {
        "$oid": "538420b2862a656e9e99fc93"
    },
    "name": "Farmer John",
    "items": {
        "peaches": 5,
        "bananas": 10
    }
}

Let's say you wish to add `"apples": 2` to the items. The command would be

db.collection.update({"name": "Farmer John"},
                     {"$set": {"items.apples": 2}});

Your document would then look like:

{
    "_id": {
        "$oid": "538420b2862a656e9e99fc93"
    },
    "name": "Farmer John",
    "items": {
        "peaches": 5,
        "bananas": 10,
        "apples: 2
    }
}

Note that this works with inserting subdocument as well, so we can modify the original example:

{
    "_id": {
        "$oid": "538420b2862a656e9e99fc93"
    },
    "name": "Farmer John",
    "items": {
        "peaches": {
            "yellow": 5,
            "white": 3
        }
    }
}

And let's insert 4 granny smith apples and 8 fuji apples.

db.collection.update({"name": "Farmer John"},
                     {"$set": {"items.apples": {"fuji": 8, "granny smith": 4}}});

Our document would now be:

{
    "_id": {
        "$oid": "538420b2862a656e9e99fc93"
    },
    "name": "Farmer John",
    "items": {
        "peaches": {
            "yellow": 5,
            "white": 3
        },
        "apples": {
            "fuji": 8,
            "granny smith": 4
        }
    }
}

One last comment: note that if the subdocument or field already exists, then it will be overridden by the `$set` command.

Problem

Here's an example of what I'm trying to do, as I can't explain what I mean. I execute this in the mongo CLI: `db.posts.insert({name: "Hello, world!, body: "Here's my first blog post. Happy reading!", comments: []})`. What I want to do is update that entry to add a comment to the `comments` dictionary. How would I achieve this using `db.posts.update()`?

Original source