簡體   English   中英

Mongodb,從數組中查找結果並移動到另一個數組

[英]Mongodb,find results from array and move to another array

例如:

{
  "groups": [
    ...,
    {
      "id": 1,
      "name": "g1",
      "items": [
        {
          "id": 11,
          "name": "item-11"
        },
        {
          "id": 12,
          "name": "item-12"
        }
      ]
    },
    {
      "_id": 2,
      "name": "g2",
      "items": []
    }
  ]
}

使用'更新',groups[0].items 搜索結果,移動到groups[1].items。

預期結果:

{
  "groups": [
    {
      "_id": 2,
      "name": "g2",
      "items": [
        {
          "id": 11,
          "name": "item-11"
        },
        {
          "id": 12,
          "name": "item-12"
        }
      ]
    }
  ]
}

根據對這個問題的回答,在更新中使用另一個字段的值的唯一方法似乎是創建一個腳本。 您尚未指定對groups[0].items的預期內容,因此我將其設置為空數組:

var requests = [];
var cursor = db.getCollection('collection_name').find({});
cursor.forEach(document => { 
    requests.push( { 
        'updateOne': {
            'filter': { '_id': document._id },
            'update': { '$set': { 
                'groups.1.items': document.groups[0].items,
                'groups.0.items': []
                 } 
            }
        }
    });
    if (requests.length === 500) {
        //Execute per 500 operations and re-init
        db.getCollection("collection_name").bulkWrite(requests);
        requests = [];
    }
});

if(requests.length > 0) {
     db.getCollection("collection_name").bulkWrite(requests);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM