[MongoDB] Insert new data as first index in existing Array

For instance if i have following simple data:

{ "_id" : ObjectId("56a9d168e7d029513ded52f3"), "first_roof" : [ { "seq" : [ "John", "Ben", "Lee" ] } ] }

Then to add/update array namely seq by using this query:

db.test.update({_id: ObjectId("56a9d168e7d029513ded52f3")} , {$push: {'first_roof.0.seq': { $each: ["Omar"], $position: 0  } }    } );


  • 56a9d168e7d029513ded52f3 : is ID for document that i want to modify.
  • $push : mongodb modifier to append data with target position that i want to change.
  • first_roof.0.seq: Injecting data into first index of array seq that located on first index of array first_roof
  • $each: specifying data that will be appended.
  • $position: use index 0 if you want to insert as first element.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s