在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 } );
当前回答
(我本想把这篇文章作为评论,但我做不到)
对于登陆这里试图使用c#驱动程序更新文档中的另一个字段的任何人… 我不知道如何使用任何UpdateXXX方法及其相关重载,因为它们将UpdateDefinition作为参数。
// we want to set Prop1 to Prop2
class Foo { public string Prop1 { get; set; } public string Prop2 { get; set;} }
void Test()
{
var update = new UpdateDefinitionBuilder<Foo>();
update.Set(x => x.Prop1, <new value; no way to get a hold of the object that I can find>)
}
作为一种变通方法,我发现可以在IMongoDatabase (https://docs.mongodb.com/manual/reference/command/update/#dbcmd.update)上使用RunCommand方法。
var command = new BsonDocument
{
{ "update", "CollectionToUpdate" },
{ "updates", new BsonArray
{
new BsonDocument
{
// Any filter; here the check is if Prop1 does not exist
{ "q", new BsonDocument{ ["Prop1"] = new BsonDocument("$exists", false) }},
// set it to the value of Prop2
{ "u", new BsonArray { new BsonDocument { ["$set"] = new BsonDocument("Prop1", "$Prop2") }}},
{ "multi", true }
}
}
}
};
database.RunCommand<BsonDocument>(command);
其他回答
对于活动频繁的数据库,您可能会遇到更新会影响主动更改记录的问题,因此我建议使用snapshot()
db.person.find().snapshot().forEach( function (hombre) {
hombre.name = hombre.firstName + ' ' + hombre.lastName;
db.person.save(hombre);
});
http://docs.mongodb.org/manual/reference/method/cursor.snapshot/
最好的方法是在4.2+版本中,它允许在更新文档中使用聚合管道和updateOne、updateMany或update(在大多数语言驱动程序中已弃用,如果不是所有语言驱动程序)收集方法。
MongoDB 4.2 +
4.2版还引入了$set管道阶段操作符,它是$addFields的别名。我将在这里使用$set,因为它与我们试图实现的目标相映射。
db.collection.<update method>(
{},
[
{"$set": {"name": { "$concat": ["$firstName", " ", "$lastName"]}}}
]
)
请注意,该方法的第二个参数中的方括号指定了一个聚合管道,而不是一个普通的更新文档,因为使用简单的文档将无法正确工作。
MongoDB 3.4 +
在3.4+中,您可以使用$addFields和$out聚合管道操作符。
db.collection.aggregate(
[
{ "$addFields": {
"name": { "$concat": [ "$firstName", " ", "$lastName" ] }
}},
{ "$out": <output collection name> }
]
)
注意,这不会更新您的集合,而是替换现有的集合或创建一个新的集合。此外,对于需要“类型转换”的更新操作,您将需要客户端处理,并且根据操作的不同,您可能需要使用find()方法而不是.aggreate()方法。
MongoDB 3.2和3.0
这样做的方法是通过$ projection我们的文档,并使用$concat字符串聚合操作符返回连接的字符串。 然后迭代游标并使用$set更新操作符将新字段添加到文档中,使用批量操作以获得最大效率。
聚合查询:
var cursor = db.collection.aggregate([
{ "$project": {
"name": { "$concat": [ "$firstName", " ", "$lastName" ] }
}}
])
MongoDB 3.2或更新版本
您需要使用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);
}
MongoDB 2.6和3.0
从这个版本开始,您需要使用现在已弃用的Bulk API及其相关方法。
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();
}
MongoDB 2.4
cursor["result"].forEach(function(document) {
db.collection.update(
{ "_id": document._id },
{ "$set": { "name": document.name } }
);
})
我尝试了上面的解决方案,但我发现它不适合大量数据。然后我发现了流的特性:
MongoClient.connect("...", function(err, db){
var c = db.collection('yourCollection');
var s = c.find({/* your query */}).stream();
s.on('data', function(doc){
c.update({_id: doc._id}, {$set: {name : doc.firstName + ' ' + doc.lastName}}, function(err, result) { /* result == true? */} }
});
s.on('end', function(){
// stream can end before all your updates do if you have a lot
})
})
从Mongo 4.2开始,db.collection.update()可以接受一个聚合管道,最终允许基于另一个字段更新/创建一个字段:
// { firstName: "Hello", lastName: "World" }
db.collection.updateMany(
{},
[{ $set: { name: { $concat: [ "$firstName", " ", "$lastName" ] } } }]
)
// { "firstName" : "Hello", "lastName" : "World", "name" : "Hello World" }
第一部分{}是匹配查询,过滤要更新的文档(在本例中是所有文档)。 第二部分[{$set: {name:{…}}]是更新聚合管道(注意方括号表示使用聚合管道)。$set是一个新的聚合操作符,是$addFields的别名。
MongoDB 4.2+ Golang
result, err := collection.UpdateMany(ctx, bson.M{},
mongo.Pipeline{
bson.D{{"$set",
bson.M{"name": bson.M{"$concat": []string{"$lastName", " ", "$firstName"}}}
}},
)