MongoDb批量操作获取ID [英] MongoDb bulk operation get id
问题描述
我想通过MongoDb执行批量操作.如何获取将在其后返回的ID数组?
I want to perform bulk operation via MongoDb. How to get array of Ids that will be returned after it?
我可以在不使用批量操作的情况下更快地执行单操作插入吗?您能建议我其他方法吗?
我正在使用C# mongoDb driver 2.0
和MongoDb v. 3.0.2
Can i perform single-operation insert faster without using bulk ? Can you advise me some other approach ?
I'm using C# mongoDb driver 2.0
and MongoDb v. 3.0.2
更新:
我找到了以下解决方案-保存mongo集合的最大ObjectId
update:
I found the following solution - save maximum ObjectId
of mongo collection,
db.col.find().sort({_id:-1}).limit(1).pretty()
,并在插入后执行相同的操作 这样我们就可以获得插入文档的范围,这有意义吗?
and do the same after insert So we will get the range of inserted documents, does it make a sense?
推荐答案
您可以使用带有InsertManyAsync
的新驱动程序批量插入项目.如果您希望驱动程序为这些项目生成的ID,则只需在插入项目后将它们从项目本身中取出即可.例如:
You can insert items in bulk using the new driver with InsertManyAsync
. If you want the Ids that the driver generated for these items you can simply get them out of the items themselves after they are inserted. For example:
Hamster[] hamsters = { new Hamster { Name = "Vaska" }, new Hamster { Name = "Petzka" } };
await collection.InsertManyAsync(hamsters);
var insertedIDs = hamsters.Select(_ => _.Id);
这篇关于MongoDb批量操作获取ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!