[mongodb] 하나의 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'

그리고 업데이트되지 않습니다. 업데이트하려면 어떻게해야합니까?



답변

업데이트 할 수 없습니다. new를 사용하여 문서를 저장 _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.indexOf ( “2019 :”)! = 0) {… forEach는 사용 된 .snapshot () 메서드를 통해서도 삽입 된 문서를 선택하므로 무한 루프를 방지해야했습니다 .


답변

여기 루프와 오래된 문서 제거에 대한 여러 요청을 피하는 솔루션이 있습니다.

다음과 같은 방법을 사용하여 수동으로 새로운 아이디어를 쉽게 만들 수 있습니다. _id:ObjectId()
그러나 Mongo가 _id가 없으면 자동으로 할당한다는 것을 알면 집계를 사용 $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원하는 값을 설정할 수도 있습니다.


답변