在 MongoDB 中,是否可以使用来自另一个字段的值来更新字段的值?等效的 SQL 类似于:
UPDATE Person SET Name = FirstName + ' ' + LastName
MongoDB 伪代码将是:
db.person.update( {}, { $set : { name : firstName + ' ' + lastName } );
最佳答案
最好的方法是在 4.2+ 版本中,它允许在 update 文档和 updateOne
中使用聚合管道。 , updateMany
, 或 update
(在大多数语言驱动程序中已弃用)收集方法。
4.2 版还引入了 $set
管道阶段运算符,它是 $addFields
的别名.我将在这里使用 $set
,因为它与我们想要实现的目标映射。
db.collection.<update method>(
{},
[
{"$set": {"name": { "$concat": ["$firstName", " ", "$lastName"]}}}
]
)
请注意,该方法的第二个参数中的方括号指定了聚合管道而不是普通的更新文档,因为使用简单的文档不会正常工作。
在 3.4+ 中,您可以使用 $addFields
和 $out
聚合管道运算符。
db.collection.aggregate(
[
{ "$addFields": {
"name": { "$concat": [ "$firstName", " ", "$lastName" ] }
}},
{ "$out": <output collection name> }
]
)
请注意,此不会更新您的集合,而是替换现有集合或创建一个新集合。此外,对于需要 "typecasting" 的更新操作,您将需要客户端处理,根据操作的不同,你可能需要使用 find()
方法而不是 .aggreate()
方法。
我们这样做的方式是 $project
阅读我们的文件并使用 $concat
字符串聚合运算符返回连接的字符串。
然后迭代 光标 并使用 $set
更新运算符以使用 批量操作 将新字段添加到您的文档中以实现最高效率。
var cursor = db.collection.aggregate([
{ "$project": {
"name": { "$concat": [ "$firstName", " ", "$lastName" ] }
}}
])
您需要使用 bulkWrite
方法。
var requests = [];
cursor.forEach(document => {
requests.push( {
'updateOne': {
'filter': { '_id': document._id },
'update': { '$set': { 'name': document.name } }
}
});
if (requests.length === 500) {
//Execute per 500 operations and re-init
db.collection.bulkWrite(requests);
requests = [];
}
});
if(requests.length > 0) {
db.collection.bulkWrite(requests);
}
从此版本开始,您需要使用现已弃用的 Bulk
API 及其 associated methods .
var bulk = db.collection.initializeUnorderedBulkOp();
var count = 0;
cursor.snapshot().forEach(function(document) {
bulk.find({ '_id': document._id }).updateOne( {
'$set': { 'name': document.name }
});
count++;
if(count%500 === 0) {
// Excecute per 500 operations and re-init
bulk.execute();
bulk = db.collection.initializeUnorderedBulkOp();
}
})
// clean up queues
if(count > 0) {
bulk.execute();
}
cursor["result"].forEach(function(document) {
db.collection.update(
{ "_id": document._id },
{ "$set": { "name": document.name } }
);
})
https://stackoverflow.com/questions/3974985/