【问题标题】:How do I prepend an object to the top position of an array?如何将对象添加到数组的顶部位置?
【发布时间】:2017-04-18 10:46:43
【问题描述】:

如果我在 MongoDb 文档中有以下数组:

"example": {
    [
        "number": 5,
        "someValue": "V"
    ],
    [
        "number": 7,
        "someValue": "H"
    ]
}

我如何将下面的数组添加到上面的数组的顶部:

[
     "number": 3,
     "someValue": "S"
]

这样原来的数组就变成了:

"example": {
    [
        "number": 3,
        "someValue": "S"
    ],
    [
        "number": 5,
        "someValue": "V"
    ],
    [
        "number": 7,
        "someValue": "H"
    ]
}

【问题讨论】:

    标签: arrays mongodb position push prepend


    【解决方案1】:

    您可以使用 $push 运算符的选项来实现这一点,如下所示:

    db.collection.update({},
    {  
       $push:{  
          "arr":{  
             $each:[  
                {  
                   "number": 3,
                   "someValue": "S"
                }
             ],
             $position: 0
          }
       }
    })
    

    $position 指定将插入元素的位置。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-02
      • 1970-01-01
      • 1970-01-01
      • 2020-05-24
      • 1970-01-01
      • 2014-09-14
      相关资源
      最近更新 更多