【问题标题】:Push element in any position of array in the subdocument将元素推送到子文档中数组的任意位置
【发布时间】:2014-05-28 09:53:31
【问题描述】:

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

文档架构:

{
  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 中可以吗?

【问题讨论】:

  • 新运算符的良好使用示例

标签: mongodb mongoose mongodb-query


【解决方案1】:

在你的问题中这是一个公平的提议,但是你基本上是错误的概念。

首先是您错过了这样一个概念,即数组的条目通常从第一个元素的索引0 开始,因此您的“定位”超出了一个单位 在这种情况下,应该是:

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

既然您现在插入到正确的位置,那么您的元素就在正确的位置。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-12
    • 2012-09-28
    • 2016-11-03
    • 2019-09-01
    • 2018-05-17
    • 1970-01-01
    • 2015-06-08
    相关资源
    最近更新 更多