How to insert a key/value to a embedded document in array?

45 views
Skip to first unread message

Pluse Paris

unread,
Jun 30, 2016, 8:32:19 AM6/30/16
to mongodb-user
How to insert a key/value to a embedded document in array?and how about batch insert?
for example:
{
   "device" : [ 
        {
            "_id" : "value1",
            "os" : "value2",
        }
}

All I want to do is add another key/value in "device" like:
{
   "device" : [ 
        {
            "_id" : "value1",
            "os" : "value2",
            "number" : "value3"
        }
}

Wan Bachtiar

unread,
Jul 12, 2016, 9:40:12 PM7/12/16
to mongodb-user

How to insert a key/value to a embedded document in array?

Hi Pluse,

You can add a new field into an embedded document in array using the positional $ operator. The operator identifies an element in an array to update without explicitly specifying the position of the element in the array. Also see Update documents in an array

For example, to add a field ‘number’ into the embedded document array of _id: 'value1':

db.collection.update(
    {"device._id":"value1"}, 
    {$set:
        {"device.$.number":"value3"}
    }
)

Also see $set operator for more information on $set.

how about batch insert?

If you are referring to adding multiple fields with a single update, the same operators apply as the above example. For example:

db.collection.update(
    {"device._id":"value1"}, 
    {$set:
        {"device.$.number":"value3",
         "device.$.string":"value4",
        }
    }
)

If you are referring to bulk operations, please see bulk.insert() to perform a list of insert operations.

Regards,

Wan.

Reply all
Reply to author
Forward
0 new messages