插入到mongo数组的特定索引

Mat*_*ggs 11 mongodb

Mongo支持文档中的文档数组.例如,像

{_id: 10, "coll": [1, 2, 3] }
Run Code Online (Sandbox Code Playgroud)

现在,想象一下我想在任意索引处插入任意值

{_id: 10, "coll": [1, {name: 'new val'}, 2, 3] }
Run Code Online (Sandbox Code Playgroud)

我知道您可以使用$和$ set更新值,但不能插入任何内容.为了插入特定的索引而必须替换整个数组有点糟糕.

Sal*_*ali 16

2.6版开始,你终于可以做到这一点.你必须使用$ position运算符.对于您的特定示例:

db.students.update(
  { _id: 10},
  { $push: {
     coll: {
       $each: [ {name: 'new val'} ],
       $position: 1
     }
  }}
)
Run Code Online (Sandbox Code Playgroud)