WHY IT HAPPENS
Because in certain cases upsert can't automatically generate an _id for the object you are manipulating.
SOLUTION A
Use [BsonIgnoreIfDefault] in the _id field of your model.
SOLUTION B
You can manually generate an _id before to upsert using ObjectId.GenerateNewId()
MORE INFO
ORIGINAL POST
Following the official documentation, I wrote this method. When i run it I receive this cryptic error message: "A bulk write operation resulted in one or more errors". Any idea what could be causing it? Everything looks fine. I already have bulk insert and remove methods working correctly.
public bool BulkUpsertReplaceOne (List<AppModel> records,
string collectionName)
{
try
{
var bulk = _database.
GetCollection(collectionName).
InitializeUnorderedBulkOperation();
foreach(AppModel am in records)
{
IMongoQuery mongoQuery = Query.EQ ("Url", am.Url);
bulk.Find (mongoQuery).Upsert().ReplaceOne(am);
}
bulk.Execute();
return true;
}
catch(Exception e)
{
logger.Info (e.Message);
}
}
EDIT COMPLETE ERROR
at MongoDB.Driver.Operations.BulkWriteBatchResultCombiner.CreateResultOrThrowIfHasErrors (IEnumerable`1 remainingRequests) in <filename unknown>:line 0
at MongoDB.Driver.Operations.BulkMixedWriteOperation.Execute (MongoDB.Driver.Internal.MongoConnection connection) in <filename unknown>:line 0
at MongoDB.Driver.MongoCollection.BulkWrite (MongoDB.Driver.BulkWriteArgs args) in <filename unknown>:line 0
at MongoDB.Driver.BulkWriteOperation.ExecuteHelper (MongoDB.Driver.WriteConcern writeConcern) in <filename unknown>:line 0
at MongoDB.Driver.BulkWriteOperation.Execute () in <filename unknown>:line 0
at SharedLibrary.Wrappers.MongoDB.MongoDBWrapper.BulkUpsertReplaceOne (System.Collections.Generic.List`1 records, System.String collectionName) in <filename unknown>:line 0"
EDIT2
I don't know if this is related, but if I check the database after the error, only ONE item of the bulk upsert have been inserted, and hasObjectId("000000000000000000000000").
Version: MongoDB 2.6.1, MongoC# driver 2.0.1