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 に答える