当前位置: 动力学知识库 > 问答 > 编程问答 >

mongodb - How do I make Mongo findOneAndModify only a single document?

问题描述:

The documentation states that findAndModify will return multiple queries if it applies.

How do I findOne document and update it in a single call?

网友答案:

You can use:

db.coll.find({query}).limit(1).forEach(function(item)
{
   db.coll.findAndModify({_id : item._id}, update});
})

the db.coll.find will find you just one document and you can modify it.

db.coll.findOne({query}) is really db.coll.find({query}) with below syntax, and there is no performance benefit for it in mongo.

// findOne() method  body. it uses find() method in it
function (query, fields, options) {
    var cursor = this.find(query, fields, -1, 0, 0, options);
    if (!cursor.hasNext()) {
        return null;
    }
    var ret = cursor.next();
    if (cursor.hasNext()) {
        throw "findOne has more than 1 result!";
    }
    if (ret.$err) {
        throw "error " + tojson(ret);
    }
    return ret;
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: