0

次の形式のドキュメントを持つコレクション A があります。

{
  _id: 12345,
  title: "title"
}

およびドキュメント B の形式は次のとおりです。

{
  _id: 12345,
  newAttribute: "newAttribute12345"
}

コレクション A を更新して、次のようなドキュメントを作成したいと考えています。

{
  _id: 12345,
  title: "title"
  newAttribute: "newAttribute12345"
}

現時点では、私は

update({_id: doc._id}, {$set: {newAttribute: doc.newAttrubute}})

、しかし、すべてのドキュメントに対してループで 10,000 回実行する必要があります。これらのような複数のドキュメントを (_id で) 1 回の db 呼び出しで、または最も効率的な方法で更新するにはどうすればよいですか? (これは基本的に結合/一括更新属性操作です)

私はmongodb 2.6を使用しています

4

3 に答える 3

2

次のシナリオを検討してください。2 つのコレクションの名前はtitleおよびattributeです。

titleコレクションには次のドキュメントが含まれます:

[{
_id: 12345,
title: "title"
},
{
_id: 12346,
title: "title1"
}]

attributeコレクションには次のドキュメントが含まれます:

[{
_id: 12345,
newAttribute: "newAttribute12345"
},
{
_id: 12346,
newAttribute: "newAttribute12346"
},
{
_id: 12347,
newAttribute: "newAttribute12347"
}]

そして、titleこの基準をtitle._id = attribute._id使用してコレクションを更新するには、次のスクリプトでmongo 一括更新を使用します。

var bulk = db.title.initializeOrderedBulkOp(); 
var counter = 0;
db.attribute.find().forEach(function(data) {
    var updoc = {
      "$set": {}
    };
    var updateKey = "newAttribute";
    updoc["$set"][updateKey] = data.newAttribute;
    bulk.find({
      "_id": data._id
    }).update(updoc);
    counter++;
    // Drain and re-initialize every 1000 update statements
    if(counter % 1000 == 0) {
      bulk.execute();
      bulk = db.title.initializeOrderedBulkOp();
    }
  })
  // Add the rest in the queue
if(counter % 1000 != 0) bulk.execute();
于 2015-06-03T11:56:01.367 に答える