FindAndModify,返回对象数组 [英] FindAndModify, return array of Objects

查看:39
本文介绍了FindAndModify,返回对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 findAndModify 修改多个文档,然后返回修改后的新文档.我的查询是:

I'm trying to modify multiple documents with findAndModify, and then return the new Documents modified. My query is:

db.users.findAndModify({
  query: {
    _id: {
      $in: [
        ObjectId("54061f3c27afac4b44688c1d"),
        ObjectId("54061f3c27afac4b44688c1e")
      ]
    }
  },
  update: {
    $inc: {
      i: 1
    }
  },
  new: true
});

但只能检索一个文档.我的目的是修改多个文档,并全部返回.是否可以检索一组文档?

but can retrieve only one document. My aim is to modify multi documents, and return all of them. Is it possible to retrieve an array of documents?

推荐答案

这个页面中的文档,findAndModify修改并返回单个文档".如果您想使用 findAndModify 修改多个文档,您必须为每个文档运行一次.在 mongo shell 中,您可以使用一些 JavaScript 来实现,如下所示:

As explained in this page in the documents, findAndModify "modifies and returns a single document". If you want to modify multiple documents using findAndModify you will have to run it once per document. In the mongo shell, you can achieve that with some JavaScript like the following:

var oids = [ObjectId("54061f3c27afac4b44688c1d"),
            ObjectId("54061f3c27afac4b44688c1e")];
docs = [];
for (var i in oids) {
    id = oids[i];
    doc = db.e.findAndModify({
        "query": { "_id": id },
        "update": { "$inc": { "i": 1 }},
        "new": true
    });
    docs.push(doc);
}
printjson(docs);

另一个选项是使用 multi 作为选项运行 update,然后检索文档.您的代码如下所示:

The other option would be to run update using multi as an option and then retrieve the documents. Your code would look something like the following:

db.users.update(
    { "_id": {
        "$in": [ObjectId("54061f3c27afac4b44688c1d"),
                ObjectId("54061f3c27afac4b44688c1e")]
        }
    },
    { "$inc": { "i": 1 }},
    { "multi": true }
);
db.users.find(
    { "_id": {
        "$in": [ObjectId("54061f3c27afac4b44688c1d"),
                ObjectId("54061f3c27afac4b44688c1e")]
        }
    }
);

这篇关于FindAndModify,返回对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆