sourcecode

MongoDB: 하위 문서 업데이트 중

copyscript 2023. 5. 14. 10:56
반응형

MongoDB: 하위 문서 업데이트 중

다음 컬렉션이 있습니다.

[{ "_id" : 7,
   "category" : "Festival",
   "comments" : [
        {
                "_id" : ObjectId("4da4e7d1590295d4eb81c0c7"),
                "usr" : "Mila",
                "txt" : "This is a comment",
                "date" : "4/12/11"
        }
    ]
}]

내가 원하는 것은 다음과 같은 주석 내부에 새 필드를 삽입하는 것입니다.

[{ "_id" : 7,
   "category" : "Festival",
   "comments" : [
        {
                "_id" : ObjectId("4da4e7d1590295d4eb81c0c7"),
                "usr" : "Mila",
                "txt" : "This is a comment",
                "date" : "4/12/11",
                "type": "abc"  // find the parent doc with id=7 & insert this inside comments
        }
    ]
}]

설명 하위 문서에 삽입하려면 어떻게 해야 합니까?

$ 위치 연산자를 사용해야 합니다.

예:

update({ 
       _id: 7, 
       "comments._id": ObjectId("4da4e7d1590295d4eb81c0c7")
   },{
       $set: {"comments.$.type": abc}
   }, false, true
);

제가 테스트를 하지는 않았지만 당신에게 도움이 되기를 바랍니다.

사용할 문서의 구조를 변경하려면

db.collection.update(기준, objNew, upsert, multi )

인수:

criteria - query which selects the record to update;
objNew - updated object or $ operators (e.g., $inc) which manipulate the object
upsert - if this should be an "upsert"; that is, if the record does not exist, nsert it
multi - if all documents matching criteria should be updated

새 구조를 가진 새 objNew를 삽입합니다.자세한 내용은 이 항목을 확인하십시오.

$positional 연산자는 'comments' 필드가 배열이 아닌 경우에만 예상대로 작동합니다.OP의 json이 잘못된 형식이지만 배열일 수 있습니다.

문제는 현재 mongodb가 쿼리와 일치하는 배열의 첫 번째 요소만 업데이트한다는 것입니다.일치하는 모든 어레이 요소 업데이트 지원을 추가할 수 있는 RFE가 열려 있지만, https://jira.mongodb.org/browse/SERVER-1243

어레이에서 이 문제를 해결하려면 정기적으로 어레이의 요소를 찾아서 개별적으로 업데이트하면 됩니다.

언급URL : https://stackoverflow.com/questions/5646798/mongodb-updating-subdocument

반응형