Search code examples
c#mongodbmongodb-.net-driverbulkinsertmongodb-csharp-2.0

MongoDb bulk operation get id


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?


Solution

  • 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);