How to add another value to a dictionary in MongoDB?

Here is an example of what I am trying to do, as I cannot explain what I mean.

I am doing this in the CLI Mongo: db.posts.insert({name: "Hello, world!, body: "Here my first blog post. Happy reading!", comments: []}). What I want to do is update this entry to add a comment to the dictionary comments.

How can I achieve this using db.posts.update()?

+5
source share
2 answers

The question and the OP example do not match. He really wants to insert a field into an array inside the document, which means that

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

works great.

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

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

, "apples": 2 .

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

:

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

, , :

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

4 8 -.

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

:

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

: , , $set.

+6

:

{
  name: "Hello, world!",
  content: "This is my first post"
}

db.posts.update({name: "Hello, world!"}, {name: "First post"});

:

{
  title: "First post"
}

, . , .

, "" , :

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

$push , . $set.

: http://www.mongodb.org/display/DOCS/Updating

-2

All Articles