MongoDB (server v 2.6.7) with C# driver 2.0: How to get the result from InsertOneAsync

后端 未结 3 496
囚心锁ツ
囚心锁ツ 2020-12-16 02:23

I am testing MongoDB (server v 2.6.7) with the C# driver 2.0.

When I am using the insert function InsertOneAsync for a document with an _id

3条回答
  •  情深已故
    2020-12-16 03:06

    Further to @JonnyHK reply you can do the same when inserting many.

    collection.InsertManyAsync(doc, new InsertManyOptions { IsOrdered = false }).Wait();
    

    would be wrapped in try/catch;

    try
    {
        collection.InsertManyAsync(doc, new InsertManyOptions { IsOrdered = false }).Wait();
    }
    catch (AggregateException aggEx)
    {
        aggEx.Handle(x =>
        {
            var mwx = x as MongoBulkWriteException;
            return mwx != null && mwx.WriteErrors.All(e => e.Category == ServerErrorCategory.DuplicateKey);
        });
    }
    

提交回复
热议问题