如何将对象添加到数组的顶部位置?

How do I prepend an object to the top position of an array?

如果我在 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"
    ]
}

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

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

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