kittyminky
kittyminky

Reputation: 485

MongoDB Update document and add new field

I am making a simple todo-list app in Mongo

Here is an example record:

{ "_id" : ObjectId("53c6e4a86929336e097b18d6"), "list_id" : 7, "notes" : { "note_id_3" : { "description" : "buy all the bacon", "done" : false }}}

I have created a unique index on the list_id attribute (rather than having users each list accessed will have a unique list_id and the accompanying notes will be stored that way. I am trying to now add a new note to the notes hash.

Following their documentation I have tried this:

db.todos.update(
     {list_id: 7}, 
     { $push: { 
          notes: { 
            note_id_6: { “description”: “it works”, “done”: true}}}})

as well as

db.todos.update(
         {list_id: 7}, 
         { $set: { 
              "notes.note_id_6": { 
                “description”: “it works”, “done”: true}}}})

but am getting the error SyntaxError: Unexpected token ILLEGAL and I'm not sure what part of my syntax is incorrrect.

Upvotes: 0

Views: 3949

Answers (1)

Ori Dar
Ori Dar

Reputation: 19020

Use " instead of (double quotes):

db.todos.update(
 {list_id: 7}, 
 { $push: { 
      notes: { 
        note_id_6: { "description": "it works", "done": true}}}})

Also $push works on arrays. So if:

> db.todos.findOne()
{
    "_id" : ObjectId("53c6e4a86929336e097b18d6"),
    "list_id" : 7,
    "notes" : [
            {
                    "note_id" : 3,
                    "description" : "it works",
                    "done" : true
            }
    ]
}

The way to add is:

> db.todos.update({list_id: 7}, {$push: {notes: { "note_id": 4, "description": "doesn't works", "done": false}}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Upvotes: 1

Related Questions