在MongoDB中,是否可以使用另一个字段的值更新字段的值?等效的SQL应该是这样的:
UPDATE Person SET Name = FirstName + ' ' + LastName
MongoDB伪代码是:
db.person.update( {}, { $set : { name : firstName + ' ' + lastName } );
在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
pipeline stage操作符,它是$addFields
的别名.我将在这里使用$set
,因为它与我们正在努力实现的目标一致.
db.collection.<update method>(
{},
[
{"$set": {"name": { "$concat": ["$firstName", " ", "$lastName"]}}}
]
)
请注意,方法的第二个参数中的方括号定义了聚合管道,而不是普通的更新文档.使用普通文档将正确工作.
在3.4+中,可以使用$addFields
和$out
聚合管道操作符.
db.collection.aggregate(
[
{ "$addFields": {
"name": { "$concat": [ "$firstName", " ", "$lastName" ] }
}},
{ "$out": "collection" }
]
)
请注意,这does not update your collection but instead replaces the existing collection or creates a new one.也适用于需要"typecasting" you will need client-side processing,的更新操作,根据操作的不同,您可能需要使用find()
方法而不是.aggreate()
方法.
我们实现这一点的方法是对文档进行$project
次排序,并使用$concat
字符串聚合运算符返回连接的字符串.
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 } }
);
})