Push element in any position of array in the subdocument

余生颓废 提交于 2020-01-11 12:37:06

问题


In MongoDB 2.6 we can use $position (http://docs.mongodb.org/master/reference/operator/update/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:3 } }});

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']
  }
}

Is it possible in MongoDB 2.6?


回答1:


It's a fair proposition in your question, however you basically have the concept wrong.

The first of which is that you have missed the concept that arrays in general have their entries starting at an index of 0 for the first element, so your "positioning" is out by one unit in this case and should have been:

db.collection.update(
   { _id: tsId },
   {$push: { 'subdoc.array': { "$each":["3", "4"], "$position": 3 } }}
)

And since you are now inserting at the correct position, then your elements are in the correct place.



来源:https://stackoverflow.com/questions/23060079/push-element-in-any-position-of-array-in-the-subdocument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!