programing

1개의 MongoDB 문서의 _id를 갱신하는 방법

madecode 2023. 4. 1. 23:22
반응형

1개의 MongoDB 문서의 _id를 갱신하는 방법

업데이트하고 싶다_id하나의 문서 필드.별로 좋은 연습이 아니라는 거 알아하지만 기술적인 이유로 업데이트해야 합니다.

업데이트를 시도하면 다음과 같은 메시지가 나타납니다.

db.clients.update({ _id: ObjectId("123")}, { $set: { _id: ObjectId("456")}})

Performing an update on the path '_id' would modify the immutable field '_id'

업데이트는 거부됩니다.업데이트 방법

업데이트할 수 없습니다.새 파일을 사용하여 문서를 저장해야 합니다._id오래된 문서를 삭제합니다.

// store the document in a variable
doc = db.clients.findOne({_id: ObjectId("4cc45467c55f4d2d2a000002")})

// set a new _id on the document
doc._id = ObjectId("4c8a331bda76c559ef000004")

// insert the document, using the new _id
db.clients.insert(doc)

// remove the document with the old _id
db.clients.remove({_id: ObjectId("4cc45467c55f4d2d2a000002")})

전체 컬렉션에 대해 이 작업을 수행하려면 루프를 사용할 수도 있습니다(Niels 예제 참조).

db.status.find().forEach(function(doc){ 
    doc._id=doc.UserId; db.status_new.insert(doc);
});
db.status_new.renameCollection("status", true);

이 경우 UserId는 사용하고 싶은 새로운 ID입니다.

동일한 컬렉션에서 _id 이름을 변경하는 경우(예를 들어 일부 _id 접두사를 붙이는 경우)

db.someCollection.find().snapshot().forEach(function(doc) { 
   if (doc._id.indexOf("2019:") != 0) {
       print("Processing: " + doc._id);
       var oldDocId = doc._id;
       doc._id = "2019:" + doc._id; 
       db.someCollection.insert(doc);
       db.someCollection.remove({_id: oldDocId});
   }
});

if ( doc . _ id . index Of ( " '2019 : ) != 0 ) {...}는 무한 루프를 방지하기 위해 필요합니다.각각은 삽입된 문서를 선택하기 때문입니다.사용되는 throught . ( )메서드도 마찬가지입니다.

여기에는 루프 및 오래된 문서 삭제에 대한 여러 요청을 피할 수 있는 솔루션이 있습니다.

다음과 같은 방법으로 새로운 아이디어를 수동으로 쉽게 작성할 수 있습니다._id:ObjectId()그러나 Mongo가 누락된 경우 자동으로 _id를 할당한다는 것을 알고 있으면 집계를 사용하여 complete를 생성할 수 있습니다.$project문서의 모든 필드를 포함하지만 _id 필드는 생략합니다.그런 다음 다음을 사용하여 저장할 수 있습니다.$out

따라서 문서가 다음과 같은 경우:

{
"_id":ObjectId("5b5ed345cfbce6787588e480"),
"title": "foo",
"description": "bar"
}

그 후, 다음과 같이 문의합니다.

    db.getCollection('myCollection').aggregate([
        {$match:
             {_id: ObjectId("5b5ed345cfbce6787588e480")}
        }        
        {$project:
            {
             title: '$title',
             description: '$description'             
            }     
        },
        {$out: 'myCollection'}
    ])

또한 MongoDB 나침반 또는 명령을 사용하여 새 문서를 만들고specific _id원하는 가치를 제공합니다.

위의 답변에 대한 매우 작은 개선 사항으로 다음을 사용할 것을 제안합니다.

let doc1 = {... doc};

그리고나서

db.dyn_user_metricFormulaDefinitions.deleteOne({_id: doc._id});

이렇게 하면 오래된 _id를 유지하기 위해 추가 변수를 생성할 필요가 없습니다.

위 @Forent Arlandis의 약간 변경된 예에서는 문서에 다른 필드의 _id를 삽입합니다.

 > db.coll.insertOne({ "_id": 1, "item": { "product": { "id": 11 } },   "source": "Good Store" })
 { "acknowledged" : true, "insertedId" : 1 }
 > db.coll.aggregate( [ { $set: { _id : "$item.product.id" }}, { $out: "coll" } ]) // inserting _id you want for the current collection
 > db.coll.find() // check that _id is changed
 { "_id" : 11, "item" : { "product" : { "id" : 11 } }, "source" : "Good Store" }

사용 안 함$match필터 +$out@Forent Arlandis의 답변과 같이 $out은 집계 결과를 삽입하기 전에 수집 데이터를 완전히 삭제하기 때문에 실제로는 일치하지 않는 모든 데이터가 손실됩니다.$match필터

언급URL : https://stackoverflow.com/questions/4012855/how-to-update-the-id-of-one-mongodb-document

반응형