Is array index position in MongoDB document guaranteed to be maintained for $push operations?

323 views
Skip to first unread message

Mayank Jain

unread,
Apr 21, 2016, 6:37:52 AM4/21/16
to mongodb-user
Hi,

I checked the MongoDB docs but couldn't find the answer to this question.
Is the array index position guaranteed to remain same if you only do $push operations on it?

Example query
db.example.findAndModify({query: { name: "test"},
                         update: { $push: { "mapping.s": "free" }},
                         upsert: true,
                         new: true})


Can the application use the index of the array reliably in this case when fetching the whole doc based on its name?

I am using MongoDB 3.2.x version

Thanks.

Mayank Jain

unread,
Apr 24, 2016, 1:34:46 PM4/24/16
to mongodb-user
Any updates?

Rhys Campbell

unread,
Apr 25, 2016, 3:24:11 AM4/25/16
to mongodb-user
From the manual...

"The $position modifier specifies the location in the array at which the $push operator insert elements. Without the $position modifier, the $push operator inserts elements to the end of the array. See $push modifiers for more information."


I would say that this means order will be preserved in insert order if you don;t use the $position modifier. There's always the option of using the $position modifier with an index if you wish to be explicit. 

Mayank Jain

unread,
Apr 25, 2016, 4:34:12 AM4/25/16
to mongodb-user
I thought the same but just wanted to make sure since it does not say this explicitly.
Thanks.
Reply all
Reply to author
Forward
0 new messages