在子文档中的数组的任何位置推送元素

时间:2014-04-14 12:27:35

标签: mongodb mongoose mongodb-query

在MongoDB 2.6中,我们可以使用$positionhttp://docs.mongodb.org/master/reference/operator/update/position/)修饰符来指定在文档中更新数组期间阵列中的位置。但我想在子文档中插入一个数组。

文件架构:

{
  subdoc: {
    array: ['0', '1', '2', '5', '6']
  }
}

以下更新会推送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中使用?

1 个答案:

答案 0 :(得分:3)

这在你的问题中是一个公平的主张,但你基本上都有错误的概念。

第一个是你错过了一般来说数组的第一个元素的索引为0的概念,所以你的“定位”是一个单位< / strong>在这种情况下应该是:

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

由于您现在正在插入正确的位置,因此您的元素位于正确的位置。