在 MongoDB 中,是否可以使用来自另一个字段的值来更新字段的值?等效的 SQL 类似于:
UPDATE Person SET Name = FirstName + ' ' + LastName
MongoDB 伪代码将是:
db.person.update( {}, { $set : { name : firstName + ' ' + lastName } );
最好的方法是在 4.2+ 版本中,它允许在 update 文档和 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> }
]
)
请注意,此不会更新您的集合,而是替换现有集合或创建一个新集合。此外,对于需要 "typecasting" 的更新操作,您将需要 client-侧处理,并且根据操作,您可能需要使用 find()
方法而不是 .aggreate()
方法。
MongoDB 3.2 和 3.0
我们执行此操作的方法是$project
处理我们的文档并使用 $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 及其 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();
}
MongoDB 2.4
cursor["result"].forEach(function(document) {
db.collection.update(
{ "_id": document._id },
{ "$set": { "name": document.name } }
);
})
你应该迭代。对于您的具体情况:
db.person.find().snapshot().forEach(
function (elem) {
db.person.update(
{
_id: elem._id
},
{
$set: {
name: elem.firstname + ' ' + elem.lastname
}
}
);
}
);
save()
完全替换了文档。应该改用 update()
。
db.person.update( { _id: elem._id }, { $set: { name: elem.firstname + ' ' + elem.lastname } } );
怎么样
create_guid
的函数,当以这种方式使用 forEach
迭代时,它只为每个文档生成一个唯一的 guid(即,简单地在 update
语句中使用 create_guid
和 mutli=true
会导致为所有文件)。这个答案对我来说非常有效。 +1
显然,自 MongoDB 3.4 起就有一种方法可以有效地做到这一点,请参阅 styvane's answer。
以下已过时的答案
您不能在更新中引用文档本身(目前)。您需要遍历文档并使用函数更新每个文档。有关示例,请参阅 this answer,或有关服务器端 eval()
的 this one。
update
操作中对当前文档的引用的内容。 This related feature request 也仍未解决。
OPEN
中。
对于具有高活动性的数据库,您可能会遇到更新影响主动更改记录的问题,因此我建议使用 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/
snapshot()
:Deprecated in the mongo Shell since v3.2. Starting in v3.2, the $snapshot operator is deprecated in the mongo shell. In the mongo shell, use cursor.snapshot() instead.
link
从 Mongo 4.2
开始,db.collection.update()
可以接受聚合管道,最终允许基于另一个字段更新/创建一个字段:
// { firstName: "Hello", lastName: "World" }
db.collection.update(
{},
[{ $set: { name: { $concat: [ "$firstName", " ", "$lastName" ] } } }],
{ multi: true }
)
// { "firstName" : "Hello", "lastName" : "World", "name" : "Hello World" }
第一部分 {} 是匹配查询,过滤要更新的文档(在我们的例子中是所有文档)。
第二部分 [{ $set: { name: { ... } }] 是更新聚合管道(注意方括号表示使用聚合管道)。 $set 是一个新的聚合运算符和 $addFields 的别名。
不要忘记 { multi: true },否则只会更新第一个匹配的文档。
{}
是过滤部分:例如,您可能想要更新 doc1
和 doc2
而不是 doc3
。如果没有第三部分,默认情况下,更新将仅应用于 1 个文档,例如 doc1
,并且不会更新 doc2
。请注意,您也可以使用 db.collection.updateMany
去掉第三个参数。
我尝试了上述解决方案,但发现它不适合大量数据。然后我发现了流功能:
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
})
})
update()
方法将聚合管道作为参数,例如
db.collection_name.update(
{
// Query
},
[
// Aggregation pipeline
{ "$set": { "id": "$_id" } }
],
{
// Options
"multi": true // false when a single doc has to be updated
}
)
可以使用聚合管道使用现有值设置或取消设置该字段。
注意:使用 $
和字段名称来指定必须读取的字段。
以下是我们为约 150_000 条记录将一个字段复制到另一个字段的方法。它花了大约 6 分钟,但与实例化和迭代相同数量的 ruby 对象相比,它的资源密集度仍然明显降低。
js_query = %({
$or : [
{
'settings.mobile_notifications' : { $exists : false },
'settings.mobile_admin_notifications' : { $exists : false }
}
]
})
js_for_each = %(function(user) {
if (!user.settings.hasOwnProperty('mobile_notifications')) {
user.settings.mobile_notifications = user.settings.email_notifications;
}
if (!user.settings.hasOwnProperty('mobile_admin_notifications')) {
user.settings.mobile_admin_notifications = user.settings.email_admin_notifications;
}
db.users.save(user);
})
js = "db.users.find(#{js_query}).forEach(#{js_for_each});"
Mongoid::Sessions.default.command('$eval' => js)
使用 MongoDB 4.2+ 版,更新更加灵活,因为它允许在其 update
、updateOne
和 updateMany
中使用聚合管道。您现在可以使用聚合运算符转换您的文档,然后进行更新,而无需明确声明 $set
命令(我们使用 $replaceRoot: {newRoot: "$$ROOT"}
)
在这里,我们使用聚合查询从 MongoDB 的 ObjectID“_id”字段中提取时间戳并更新文档(我不是 SQL 专家,但我认为 SQL 不提供任何自动生成的具有时间戳的 ObjectID,您必须自动创建该日期)
var collection = "person"
agg_query = [
{
"$addFields" : {
"_last_updated" : {
"$toDate" : "$_id"
}
}
},
{
$replaceRoot: {
newRoot: "$$ROOT"
}
}
]
db.getCollection(collection).updateMany({}, agg_query, {upsert: true})
{ $replaceRoot: { newRoot: "$$ROOT" } }
;这意味着自行替换文档,这是没有意义的。如果您将 $addFields
替换为其别名 $set
和 updateMany
(它是 update
的别名之一),那么您将得到与上述 this one 完全相同的答案。
$replaceRoot
是因为我们需要使用 $toDate
查询,而 $set
并没有为我们提供使用 $toDate
的方法
(我会将此作为评论发布,但不能)
对于在这里尝试使用 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);
不定期副业成功案例分享