mongodb의 중첩 배열에 데이터 삽입

Sep 28 2020

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

{
 _id:1,
 list_id:23,
 name:'list01'
 cards:[
  {
   id:3,
   name:'card01'
   categories:[{
    id:10,
    category:'section01',
    tags:[{id:11,name:'tag01',is_selected: true}]
  }] 
  }
 ]
}

주어진 list_id 에 대해 선택한 범주의 태그 배열에 일부 데이터를 삽입 / 푸시해야 하지만 오류가 발생합니다.

MongoError : 위치가 너무 많습니다 (예 : '$') elements found in path 'cards.$.categories. $. tags '

이것은 내가 시도한 쿼리입니다. 이것을 달성하는 방법에 대한 아이디어 가이 쿼리의 문제점은 무엇입니까?

db.collection(TABLE)
    .updateOne(
      { list_id: 23, 'cards.categories.category': 'section01'},
      { $push: { 'cards.$.categories.$.tags': { name: 'tag02', id: uuidv4(), is_selected: true } } }
    );

답변

1 turivishal Sep 28 2020 at 14:06

여러 $ 위치를 사용할 수 없습니다. 귀하의 경우에는 단일 위치 및 https://docs.mongodb.com/manual/reference/operator/update/positional-filtered/,

필터링 된 위치 연산자 $[<identifier>]는 업데이트 작업에 대한 arrayFilters 조건과 일치하는 배열 요소를 식별합니다.

db.collection(TABLE).updateOne({
  list_id: 23,
  "cards.categories.category": "section01"
},
{
  $push: { "cards.$.categories.$[elem].tags": {
      name: "tag02",
      id: uuidv4(),
      is_selected: true
    }
  }
},
{
  arrayFilters: [
    { "elem.category": "section01" }
  ]
})

https://mongoplayground.net/p/tZqU1RX7JOW

1 chakwok Sep 28 2020 at 13:59

요컨대 불가능합니다.

중첩 배열

위치 $ operator cannot be used for queries which traverse more than one array, such as queries that traverse arrays nested within other arrays, because the replacement for the $ 자리 표시자는 단일 값입니다.

https://docs.mongodb.com/manual/reference/operator/update/positional/

그러나 $ []를 시도해 볼 수 있습니다.

중첩 배열 필터링 된 위치 연산자 $ []는 둘 이상의 배열 및 중첩 배열을 순회하는 쿼리에 사용할 수 있습니다.

예제는 $ []와 함께 중첩 배열 업데이트를 참조하십시오.

https://docs.mongodb.com/manual/reference/operator/update/positional-filtered/#position-nested-arrays-filtered

1 AlexisG Sep 28 2020 at 14:06

당신이 사용할 수있는 https://docs.mongodb.com/manual/reference/operator/update/positional-filtered/#position-nested-arrays-filtered

db.collection.update({
  "list_id": 23,
  "cards.categories.category": "section01"
},
{
  $push: {
    "cards.$.categories.$[elem].tags": {
      name: "tag02",
      id: uuidv4(),
      is_selected: true
    }
  }
},
{
  arrayFilters: [
    {
      "elem.category": "section01"
    }
  ],
  multi: true
})

시도 해봐 https://mongoplayground.net/p/YWOetb3FR8i