将元素从$ pull移动到另一个数组

时间:2013-11-08 08:47:00

标签: mongodb

我在同一个集合中有很多文档,如下所示:

{
  "_id": ObjectId("4d525ab2924f0000000022ad"),
  "array": [
    { id: 1, other: 23 },
    { id: 1, other: 21 },
    { id: 0, other: 235 },
    { id: 1, other: 765 }
  ],
  "zeroes": []
}

我希望它们看起来像这样:

{
  "_id": ObjectId("4d525ab2924f0000000022ad"),
  "array": [
    { id: 1, other: 23 },
    { id: 1, other: 21 },
    { id: 1, other: 765 }
  ],
  "zeroes": [
    { id: 0, other: 235 }
  ]
}

基本上,我希望能够在数组中提取一些元素,并将其推送到另一个数组。我知道我可以使用$pull有条件地从数组中删除元素,但是可以重新定位这些拉取的元素吗?

1 个答案:

答案 0 :(得分:1)

不是真的。您可以使用光标进行此操作。

db.foo.find({}).forEach(function(doc) {
    doc.zeros = doc.array.filter(function(x) { return x.id == 0 });
    doc.array = doc.array.filter(function(x) { return x.id != 0 });
    db.foo.save(doc)};
)
相关问题