Upserting in Mongo DB and the Id problem

前端 未结 2 2066
情书的邮戳
情书的邮戳 2021-02-12 21:59

I have a problem while upserting to mongo db using the official C# driver.

public abstract class AggregateRoot
{
    /// 
    /// All mongoDb docu         


        
2条回答
  •  故里飘歌
    2021-02-12 22:27

    I've encountered similar problem. I wanted to upsert documents using official C# driver. I had a class like this:

    public class MyClass
    {
        public ObjectId Id { get; set; }
        public int Field1 { get; set; }
        public string Field2 { get; set; }
    }
    

    In console I would write: db.collection.update({Field1: 3},{Field1: 3, Field2: "value"}) and it would work. In C# I wrote:

    collection.Update(Query.EQ("Field1", 3),
                    Update.Replace(new MyClass { Field1 = 3, Field2 = "value" }),
                    UpdateFlags.Upsert);
    

    and it didn't work! Because driver includes empty id in update statement and when I upsert second document with different value of Field1 exception E11000 duplicate key error index is thrown (in this case Mongo tries to insert a document with _id that already exists in db).

    When I generated _id by myself (like topic starter) I've encountered the same exception (mongo cannot change _id of a document) on upserting objects with existing value of Field1.

    Solution is to mark Id property by attribute [BsonIgnoreIfDefault] (and not initialize it). In this case driver omits _id field in update statement and MongoDb generates Id if it necessary.

提交回复
热议问题