2016-06-27 4 views
1

私はnodeJsアプリケーションでmongoskinを使用してmongo dbにデータを挿入しています。私は、データベースに文書の配列を挿入し、挿入されたレコードのIDをクライアントに返すという要件があります。データを挿入することはできますが、挿入されたレコードのIDを結果オブジェクトに配置できません。結果にinsertedIdsを見つけるのに役立つ必要があります。私は以下のコードを使用して一括挿入します。Bulk.Insert()-Mongoskinの挿入IDを取得します

db.collection('myCollection', function (err, collection) { 
    var bulk = collection.initializeUnorderedBulkOp(); 
    for (var i = 0; i < dataArray.length; i++) { 
     bulk.insert(dataArray[i]); 
    } 

    bulk.execute(function (err, result) { 
     //TODO: return the Ids of inserted records to the client 
     //Client will use these Ids to perform subsequent calls to the nodejs service 
    }); 
}); 

結果はBatchWriteResultオブジェクトタイプです。

答えて

1

はそのgetUpsertedIds()メソッドを呼び出すことによって、あなたのBatchWriteResult()オブジェクトに挿入された文書の_id値を取得するためにあなたを与えるであろう他のバルクAPIメソッドupsert()を使用してお勧めします。結果オブジェクトは、BulkWriteResultのドキュメントで指定されているものと同じ形式です。

Bulk.find()条件に該当する文書が存在しない場合、挿入を実行しますBulk.find.upsert()オプションを使用して、更新操作。更新文書に_idフィールドが指定されていない場合、MongoDBは_idフィールドを追加するので、BatchWriteResult()の中に挿入された文書 のIDを取得できます。

また、バルク挿入操作をキューイングする方法は、通常はメモリに蓄積されるため、通常は推奨されません。ドライバのdefault way of limiting the batches of 1000 at a timeに依存する以外のキューやメモリリソースの管理や、16MB未満の完全なバッチを管理するために、少し細かく制御する必要があります。これを行うには、データ配列のループforEach()ループを使用して、一度にバッチ数を1000に制限するカウンタを使用します。


以下がアップサートは、新しく作成されたドキュメント内のIDを返さなく挿入することを意味し

function getInsertedIds(result){ 
    var ids = result.getUpsertedIds(); 
    console.log(ids); // an array of upserted ids 
    return ids; 
} 

db.collection('myCollection',function(err,collection) { 
    var bulk = collection.initializeUnorderedBulkOp(), 
     insertedIds = [], 
     counter = 0; 

    dataArray.forEach(function (data){ 
     bulk.find(data).upsert().updateOne(data); 
     counter++; 

     if (counter % 1000 == 0) { 
      bulk.execute(function(err, result) { 
       insertedIds = getInsertedIds(result); 
       bulk = collection.initializeUnorderedBulkOp(); // reset after execute 
      });  
     } 
    }); 

    // Clean up the remaining operations in the queue which were 
    // cut off in the loop - counter not a round divisor of 1000 
    if (counter % 1000 != 0) { 
     bulk.execute(function(err, result) { 
      insertedIds = insertedIds.concat(getInsertedIds(result)); 
      console.log(insertedIds); 
     }); 
    } 
}); 
+1

上記のアプローチを示して? - そうなら、それはとても賢いです。私はそれが好きです! – profesor79

+0

最新のNode.jsドライバを使用している場合は、[** 'getInsertedIds()' **](http://mongodb.github.io/node)を使用して 'Bulk.insertしかし、[** 'BatchWriteResult' **](https://mongodb.github.io/node-mongodb-native/api-mongodb-native/2.1/api/BulkWriteResult.html#getInsertedIds)メソッドを返すので、 generated/batchwriteresult.html)、私が知っている回避策は、 'upsert()'の方法で行って、[** 'getUpsertedIds()' **](https://mongodb.github.io/node- mongodb-native/api-generated/batchwriteresult.html#getupsertedids)メソッドを使用します。説明のために – chridam

+1

thx! – profesor79

関連する問題