8

In the coupes collection in my database, an example record looks like this:

db.coupes.findOne()
{
    "_id" : ObjectId("5949834be916d79e033500c6"),
    "rank" : 10,
    "brand" : "Toyota",
    "model" : "86SE"
}

However, I'd like to update it so that it looks like the following:

 {
"_id" : ObjectId("5949834be916d79e033500c6"),
"rank" : 10,
"brand" : "Toyota",
"model" : "86SE", 
"engineSpec" : {"cylinderConfiguration": "H-4", "transmission" : "6 speed auto"}
 }

How might I accomplish this?

Donut
  • 110,061
  • 20
  • 134
  • 146
Ihor Fedchenko
  • 81
  • 1
  • 1
  • 3
  • Your question title asks about inserting a new object; however, the second example in your question has the same `ObjectId` as the first. Are you trying to update the document shown in your first example, or are you actually trying to insert a new document? – Donut Jun 21 '17 at 20:32
  • i want to add new fields – Ihor Fedchenko Jun 21 '17 at 20:40

1 Answers1

11

So, you should use 'update' method and pass there two objects: first one to find document which you are going to update and second one - update data.

As you see, I am using '$set' operator to prevent object from being totally replaced with the passed data. Learn more about update method and $set operator in official docs.

db.coupes.update(
        {
            _id: ObjectId("5949834be916d79e033500c6")
        },
        {
            $set : {
                engineSpec : {"cylinderConfiguration": "H-4", "transmission" : "6 speed auto"} }
            }
        }
    )

I used ObjectId as the only find parameter in my example, because it is updating single uniq document. Actually you can find objects by any fields, but remember that if you have multiple objects which have same field/value - you need to add multi:true option to your query to update all suitable documents:

db.coupes.update(
            {
                rank: 10
            },
            {
                $set : {
                    engineSpec : {"cylinderConfiguration": "H-4", "transmission" : "6 speed auto"} }
                }
            },
            {
                multi: true
            }
        )

Such code will update all documents where rank is equal to 10. Also you should notice that I added 'multi' option in third object, which you did not see before. Read more about update options here.

Artem Arkhipov
  • 7,025
  • 5
  • 30
  • 52
  • @IhorFedchenko , I updated my answer with new example, where I update all documents where rank is 10. Not sure if it is exactly what you asked for. – Artem Arkhipov Jun 21 '17 at 20:58
  • What if you want to update the fields of the document where it updates existing fields and adds new fields, but you may not know the names of the field names (so you can't set them explicitly). – derekshull Jul 05 '18 at 05:39