Development Tip

MongoDB의 정확한 요소 배열에서 필드 업데이트

yourdevel 2020. 11. 30. 20:04
반응형

MongoDB의 정확한 요소 배열에서 필드 업데이트


다음과 같은 구조의 문서가 있습니다.

{
    _id:"43434",
    heroes : [
        { nickname : "test",  items : ["", "", ""] },
        { nickname : "test2", items : ["", "", ""] },
    ]
}

내가 할 수있는 $set의 두 번째 요소 items배열에 포함 된 개체의 배열 herosnickname "test"?

결과:

{
    _id:"43434",
    heroes : [
        { nickname : "test",  items : ["", "new_value", ""] }, // modified here
        { nickname : "test2", items : ["", "", ""] },
    ]
}

mongodb의 위치 연산자 와 업데이트하려는 항목에 대해 숫자 인덱스를 사용하는 두 가지 개념을 사용해야 합니다.

위치 연산자를 사용하면 다음과 같은 조건을 사용할 수 있습니다.

{"heros.nickname": "test"}

그런 다음 찾은 배열 항목을 다음과 같이 참조하십시오.

{"heros.$  // <- the dollar represents the first matching array key index

"items"의 두 번째 배열 항목을 업데이트하려는 경우 배열 키가 0 인덱싱됩니다. 이것이 키 1입니다.

그래서:

> db.denis.insert({_id:"43434", heros : [{ nickname : "test",  items : ["", "", ""] }, { nickname : "test2", items : ["", "", ""] }]});
> db.denis.update(
    {"heros.nickname": "test"}, 
    {$set: {
        "heros.$.items.1": "new_value"
    }}
)
> db.denis.find()
{
    "_id" : "43434", 
    "heros" : [
        {"nickname" : "test", "items" : ["", "new_value", "" ]},
        {"nickname" : "test2", "items" : ["", "", "" ]}
    ]
}

db.collection.update(
{
heroes:{$elemMatch:{ "nickname" : "test"}}},
 {
     $push: {
        'heroes.$.items': {
           $each: ["new_value" ],
           $position: 1
        }
     }
   }

)

This solution works well. Just want to add one point. Here is the structure. I need to find OrderItemId is 'yyy' and update. If the query field in condition is an array, like below "OrderItems.OrderItemId" is array. You can not use "OrderItems.OrderItemId[0]" as operation in the query. Instead, you need to use "OrderItems.OrderItemId" to compare. Otherwise, it can not match one.

{
  _id: 'orderid',
  OrderItems: [
   {
     OrderItemId: ['xxxx'], 
    ... },
   {
     OrderItemId: ['yyyy'], 
    ...}, 
]

}
 result =  await collection.updateOne(
        { _id: orderId, "OrderItems.OrderItemId": [orderItemId] },
        { $set: { "OrderItems.$.imgUrl": imgUrl[0], "OrderItems.$.category": category } },
        { upsert: false },
      )
    console.log('  (result.modifiedCount) ', result.modifiedCount)
    console.log('  (result.matchedCount) ', result.matchedCount)

참고URL : https://stackoverflow.com/questions/10432677/update-field-in-exact-element-array-in-mongodb

반응형