【问题标题】:Inserting data to nested array in mongodb将数据插入到mongodb的嵌套数组中
【发布时间】:2021-01-13 17:53:18
【问题描述】:

我有一个看起来像这样的文档

{
 _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,我需要将一些数据插入/推送到选定 category 中的 tags 数组,但出现错误说

MongoError:在路径中找到太多位置(即“$”)元素 '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 } } }
    );

【问题讨论】:

标签: mongodb mongodb-query


【解决方案1】:

您不能使用多个 $ 位置,对于您的情况,您可以使用单个位置和arrayFilters,

过滤的位置运算符$[<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" }
  ]
})

Playground

【讨论】:

    【解决方案2】:

    简而言之,这是不可能的。

    嵌套数组

    位置 $ 运算符不能用于遍历的查询 多个数组,例如遍历嵌套数组的查询 在其他数组中,因为 $ 占位符的替换是 单个值

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

    不过,你可能想试试 $[]

    嵌套数组过滤后的位置运算符 $[] 可以是 用于遍历多个数组和嵌套数组的查询。

    有关示例,请参阅使用 $[] 更新嵌套数组。

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

    【讨论】:

      【解决方案3】:

      您可以使用$[identifier]

      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
      })
      

      试试here

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-08-24
        • 2016-07-06
        • 1970-01-01
        • 2021-06-10
        • 1970-01-01
        • 2015-04-02
        • 1970-01-01
        相关资源
        最近更新 更多