MongoDB의 정확한 요소 배열에서 필드 업데이트
다음과 같은 구조의 문서가 있습니다.
{
_id:"43434",
heroes : [
{ nickname : "test", items : ["", "", ""] },
{ nickname : "test2", items : ["", "", ""] },
]
}
내가 할 수있는 $set
의 두 번째 요소 items
배열에 포함 된 개체의 배열 heros
에 nickname
"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
'Development Tip' 카테고리의 다른 글
MySQL의 FOR UPDATE 잠금을 사용할 때 정확히 잠긴 것은 무엇입니까? (0) | 2020.11.30 |
---|---|
중복 된 'row.names'는 허용되지 않습니다. 오류 (0) | 2020.11.30 |
Node.js에 변수가 정의되어 있는지 어떻게 확인할 수 있습니까? (0) | 2020.11.30 |
중첩 된 사전의 항목에서 Pandas DataFrame 생성 (0) | 2020.11.30 |
JsonObject를 문자열로 변환 (0) | 2020.11.30 |