使用MongoDB查询根据键值更新集合中的所有文档

时间:2017-01-30 10:24:23

标签: mongodb mongodb-query

我需要使用MongoDB更新集合中的所有文档,但根据条件不同。我在下面解释我的收藏。

db_users:

{ "_id" : ObjectId("4e93037bbf6f1dd3a0a9541a"), "device_type" : "Android" },
{ "_id" : ObjectId("4e93037bbf6f1dd3a0a9541b"), "device_type" : " " }

在这里,我需要为每个文档添加一个额外的列(i.e-version),并在“device_type”:“Android”时更新version=1.0,在“device_type”时更新version='':“”

我需要查询。

2 个答案:

答案 0 :(得分:2)

我认为进行两种类型的操作不能是单个查询,但可能有两个查询

db.db_users.update({'device_type':"Android"},{$set : {'version':"1.0"}},{multi:true});
db.db_users.update({'device_type':""},{$set : {'version':""}},{multi:true});

也在文件中显示了一个空格" ",而有问题你提到它""。如果它不一致,你应该使用$或。

也可以通过单个脚本

完成
db.db_users.find().forEach(function(doc){if(doc.device_type && doc.device_type==='Android'){doc.version="1.0"}else{doc.version=""} db.db_users.save(doc)});

如果有多个逻辑,那么最好选择脚本,如果它只是你在问题中提到的限制,那么两个更新会更好。

答案 1 :(得分:1)

对于 MongoDB 3.4 和更新版本:

使用聚合框架, $addFields $out 管道将使用单个聚合操作更新您的集合。例如:

db.users.aggregate([
    {
        "$addFields": {
            "version": {
                "$switch": {
                    "branches": [
                        { "case": { "$eq": ["$device_type", "Android"] }, "then": "1.0" },
                        { "case": { "$eq": ["$device_type", " "] }, "then": "" }
                    ]
                }
            }
        }
    },
    { "$out": "users" }
])

对于 MongoDB 3.2

您可以使用 bulkWrite 方法进行更快,更有效的更新。请考虑以下操作:

var ops = [];
db.users.aggregate([
    {
        "$project": {
            "version": {
                "$cond": [
                    { "$eq": ["$device_type", "Android"] },
                    "1.0",
                    ""
                ]
            }
        }
    }
]).forEach(function(doc){
    ops.push( { 
        "updateOne": {
            "filter": { "_id": doc._id },
            "update": { "$set": { "version": doc.version } }
        }
    });
    if (ops.length === 500) {
        // Execute per 500 operations and re-initialise
        db.users.bulkWrite(ops);
        ops = [];
    }
})

if (ops.length > 0) {
     db.users.bulkWrite(ops);
}

对于 MongoDB< = 3.0和> = 2.6

var bulk = db.users.initializeUnorderedBulkOp();
var count = 0;

db.users.aggregate([
    {
        "$project": {
            "version": {
                "$cond": [
                    { "$eq": ["$device_type", "Android"] },
                    "1.0",
                    ""
                ]
            }
        }
    }
]).forEach(function(doc) { 
    bulk.find({ "_id": doc._id }).updateOne({ "$set": { "version": doc.version } });
    count++;
    if (count % 500 === 0) {
        // Excecute per 500 operations and re-initialise
        bulk.execute();
        bulk = db.users.initializeUnorderedBulkOp();
    }
})

// clean up remaining operations in queue
if (count > 0) {
    bulk.execute();
}