Info
In MongoDB 2.6 we can use $position modifier to specifies the location in the array during update of an array in a document. But I would like to insert in an array in a subdocument.
// Document schema:
{ subdoc: {
array: ['0', '1', '2', '5', '6'] } }
// The following update pushes the elements in the end of array..
db.collection.update(
{ _id: tsId },
{$push: { 'subdoc.array': { $each:['3', '4'], $position:2 } }});
// So, the result is
{ subdoc: {
array: ['0', '1', '2', '5', '6', '3', '4'] }}
// But I expect
{ subdoc: {
array: ['0', '1', '2', '3', '4', '5', '6'] }}
Top User Comments
rwander commented on Mon, 14 Apr 2014 13:13:02 +0000:
sorry for inattention, the mongodb version is 2.4.10! Please close this issue..
scotthernandez commented on Mon, 14 Apr 2014 13:08:59 +0000:
Are you sure you are using 2.6.0? Please run "db.version()" to verify that the server is 2.6.0.
I cannot reproduce this with 2.6.0 locally:
> db.version()
2.6.0
> db.a.save({ subdoc: { array: ['0', '1', '2', '5', '6'] } ,_id:1})
WriteResult({ "nMatched" : 0, "nUpserted" : 1, "nModified" : 0, "_id" : 1 })
> db.a.find()
{ "_id" : 1, "subdoc" : { "array" : [ "0", "1", "2", "5", "6" ] } }
> db.a.update({}, {$push:{"subdoc.array": {$each:['3','4'], $position:2}}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.a.find()
{ "_id" : 1, "subdoc" : { "array" : [ "0", "1", "3", "4", "2", "5", "6" ] } }