将元素推入子文档中数组的任何位置 [英] Push element in any position of array in the subdocument
问题描述
在MongoDB 2.6中,我们可以使用$position
( http://docs .mongodb.org/master/reference/operator/update/position/)修饰符,用于在文档中更新数组期间指定数组中的位置.但是我想在子文档中的数组中插入.
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.
文档架构:
{
subdoc: {
array: ['0', '1', '2', '5', '6']
}
}
以下更新将元素压入array
的末尾.
The following update pushes the elements in the end of array
..
db.collection.update(
{ _id: tsId },
{$push: { 'subdoc.array': { $each:['3', '4'], $position:3 } }});
所以,结果是
{
subdoc: {
array: ['0', '1', '2', '5', '6', '3', '4']
}
}
但是我希望
{
subdoc: {
array: ['0', '1', '2', '3', '4', '5', '6']
}
}
在MongoDB 2.6中可以吗?
Is it possible in MongoDB 2.6?
推荐答案
在您的问题中这是一个很合理的主张,但是您基本上认为这个概念是错误的.
It's a fair proposition in your question, however you basically have the concept wrong.
首先,您错过了以下概念:通常,数组的第一个元素的条目以0
的索引开头,因此您的定位"以一个单位 >在这种情况下,应该是:
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.
这篇关于将元素推入子文档中数组的任何位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!