2

我的文档结构如下:

{
   "name":"CategoryChildLevel2",
   "parentId":"2",
   "otherAttribute":"anyVal",
   "breadcrumb":[
      {
         "name":"RootCategory",
         "id":"1"
      },
      {
         "name":"CategoryChildLevel1",
         "id":"2"
      },
      {
         "name":"CategoryChildLevel2",
         "id":"3"
      }
   ]
}

我想要的是能够运行一个查询:

替换以开头的面包屑数组

      {
         "name":"RootCategory",
         "id":"1"
      },
      {
         "name":"CategoryChildLevel1",
         "id":"2"
      }

将此子序列替换为

      {
         "name":"RootCategory",
         "id":"1"
      },
      {
         "name":"AnotherCategory",
         "id":"4"
      }
      {
         "name":"AnotherCategory2",
         "id":"5"
      }

所以最终的结果是

{
   "name":"CategoryChildLevel2",
   "parentId":"2",
   "otherAttribute":"anyVal",
   "breadcrumb":[
      {
         "name":"RootCategory",
         "id":"1"
      },
      {
         "name":"AnotherCategory",
         "id":"4"
      },
      {
         "name":"AnotherCategory2",
         "id":"5"
      },
      {
         "name":"CategoryChildLevel2",
         "id":"3"
      }
   ]
}

我们可以在 MongoDB 中做到这一点吗?或者至少array startsWith使用普通查询语言或 map/reduce 检索我们应该更新(查询)的项目?

4

1 回答 1

1

从 Mongo 2.2 开始,您可以在更新的查询选择器中使用数组点表示法来执行此操作:

db.test.update({
    'breadcrumb.0.id': '1',
    'breadcrumb.1.id': '2'
}, {
    $set: {
        'breadcrumb.1': {
            name: "AnotherCategory",
            id: "4"
        }
    }
}, {multi: true})

在以前的版本中,您必须使用这样的$where查询选择器来执行update此操作:

db.test.update({
    'breadcrumb.id': '2',
    // Check the name fields as well here, if necessary.
    $where: "this.breadcrumb.length > 1 && this.breadcrumb[0].id === '1' && this.breadcrumb[1].id === '2'"
}, {
    $set: {
        'breadcrumb.1': {
            name: "AnotherCategory",
            id: "4"
        }
    }
}, { multi: true})

查询的'breadcrumb.id': '2'组件将有助于提高性能,因为它将限制慢速$where必须操作的文档数量。

于 2013-01-02T14:38:26.250 回答