programing

다른 필드의 값을 사용하여 MongoDB 필드 업데이트

bestprogram 2023. 3. 8. 21:55

다른 필드의 값을 사용하여 MongoDB 필드 업데이트

MongoDB에서는 다른 필드의 값을 사용하여 필드의 값을 갱신할 수 있습니까?동등한 SQL은 다음과 같습니다.

UPDATE Person SET Name = FirstName + ' ' + LastName

MongoDB 의사 코드는 다음과 같습니다.

db.person.update( {}, { $set : { name : firstName + ' ' + lastName } );

이를 위한 가장 좋은 방법은 버전 4.2+로 업데이트 문서의 집약 파이프라인과 (모든 언어 드라이버는 아니지만 대부분 권장되지 않음) 수집 방법을 사용할 수 있습니다.

MongoDB 4.2 이상

버전 4.2에서는 파이프라인 스테이지 연산자도 도입되었습니다.이 연산자는 에일리어스입니다.$set이 달성하려고 하는 것과 일치하고 있습니다.

db.collection.<update method>(
    {},
    [
        {"$set": {"name": { "$concat": ["$firstName", " ", "$lastName"]}}}
    ]
)

메서드의 두 번째 인수에서 대괄호는 일반 업데이트 문서 대신 집계 파이프라인을 지정하므로 단순 문서를 사용하면 제대로 작동하지 않습니다.

MongoDB 3.4 이상

이상에서는 3.4를 사용할 수 .$addFields및 집약 파이프라인 오퍼레이터.

db.collection.aggregate(
    [
        { "$addFields": { 
            "name": { "$concat": [ "$firstName", " ", "$lastName" ] } 
        }},
        { "$out": <output collection name> }
    ]
)

이렇게 하면 컬렉션이 업데이트되지 않고 기존 컬렉션이 대체되거나 새 컬렉션이 생성됩니다.또한 "typecasting"이 필요한 업데이트 작업의 경우 클라이언트 측 처리가 필요하며 작업에 따라서는find()합니다..aggreate()★★★★★★ 。

MongoDB 3.2 및 3.0

이 방법은 문서를 입력하고 문자열 집계 연산자를 사용하여 연결된 문자열을 반환하는 것입니다.그런 다음 커서를 반복하고 업데이트 연산자를 사용하여 대량 작업을 사용하여 문서에 새 필드를 추가하여 효율성을 극대화합니다.

집약 쿼리:

var cursor = db.collection.aggregate([ 
    { "$project":  { 
        "name": { "$concat": [ "$firstName", " ", "$lastName" ] } 
    }}
])

MongoDB 3.2 이후

방법을 사용해야 합니다.

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

이 버전부터는 더 이상 사용되지 않는 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 } }
    );
})

당신은 반복해야 합니다.고객 고유의 경우:

db.person.find().snapshot().forEach(
    function (elem) {
        db.person.update(
            {
                _id: elem._id
            },
            {
                $set: {
                    name: elem.firstname + ' ' + elem.lastname
                }
            }
        );
    }
);

MongoDB 3.4에서 이를 효율적으로 수행할 수 있는 방법이 있다고 합니다. 스티베인의 답변을 참조하십시오.


아래의 오래된 답변

아직 업데이트에서 문서 자체를 참조할 수 없습니다.문서를 반복하고 기능을 사용하여 각 문서를 업데이트해야 합니다.예에 대해서는 이 답변참조해 주세요.서버측의 경우는 이 답변을 참조해 주세요.eval().

액티비티가 높은 데이터베이스에서는 갱신 내용이 레코드의 변경에 영향을 주는 문제가 발생할 수 있습니다.이 때문에 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/

★★★★★Mongo 4.2는 집약 파이프라인을 받아들일 수 있으며, 최종적으로 다른 필드를 기반으로 한 필드의 갱신 또는 갱신을 허용합니다.

// { firstName: "Hello", lastName: "World" }
db.collection.updateMany(
  {},
  [{ $set: { name: { $concat: [ "$firstName", " ", "$lastName" ] } } }]
)
// { "firstName" : "Hello", "lastName" : "World", "name" : "Hello World" }
  • 은요.{}는 갱신할 문서(이 경우 모든 문서)를 필터링하는 일치 쿼리입니다.

  • 파트, 두 번째 파트입니다.[{ $set: { name: { ... } }]는 업데이트 집약 파이프라인입니다(집약 파이프라인 사용을 나타내는 각 괄호 참조).$set 는 새로운 집약 연산자이며 에일리어스입니다$addFields.

답변과 관련하여 이 업데이트에 따르면 스냅샷 기능은 버전 3.6에서 더 이상 사용되지 않습니다.따라서 버전 3.6 이상에서는 다음과 같이 작업을 수행할 수 있습니다.

db.person.find().forEach(
    function (elem) {
        db.person.update(
            {
                _id: elem._id
            },
            {
                $set: {
                    name: elem.firstname + ' ' + elem.lastname
                }
            }
        );
    }
);

위의 솔루션을 사용해 보았지만 대량의 데이터에 적합하지 않다는 것을 알게 되었습니다.그 후 스트림 기능을 발견했습니다.

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분이 걸렸지만 동일한 수의 루비 오브젝트를 인스턴스화하고 반복하는 것보다 리소스 집약도가 훨씬 낮습니다.

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 객체에서 타임스탬프를 추출합니다.ID "_id" 필드 및 문서 업데이트(SQL 전문가는 아니지만 SQL은 자동 생성된 개체를 제공하지 않는 것 같습니다).타임스탬프가 있는 ID. 해당 날짜를 자동으로 생성해야 합니다.)

var collection = "person"

agg_query = [
    {
        "$addFields" : {
            "_last_updated" : {
                "$toDate" : "$_id"
            }
        }
    },
    {
        $replaceRoot: {
            newRoot: "$$ROOT"
        } 
    }
]

db.getCollection(collection).updateMany({}, agg_query, {upsert: true})

(댓글을 달았으면 좋았을 텐데)

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>)
}

회피책으로 다음 명령어를 사용할 수 있습니다.RunCommand에 대한 방법IMongoDatabase(https://docs.mongodb.com/manual/reference/command/update/ #dbcmd.update).

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);

MongoDB 4.2+골랑

result, err := collection.UpdateMany(ctx, bson.M{},
    mongo.Pipeline{
        bson.D{{"$set",
          bson.M{"name": bson.M{"$concat": []string{"$lastName", " ", "$firstName"}}}
    }},
)
        

언급URL : https://stackoverflow.com/questions/3974985/update-mongodb-field-using-value-of-another-field