Для 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();
}