MongoDb bulk operation get id

2019-07-09 02:26发布

I want to perform bulk operation via MongoDb. How to get array of Ids that will be returned after it?

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

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?

1条回答
狗以群分
2楼-- · 2019-07-09 02:40

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);
查看更多
登录 后发表回答