Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm attempting to upsert a document into MongoDB 2.4.4 using the .NET driver. It seems not to automatically generate the _id on upserts, though it does correctly generate the _id on plain inserts. How can I cause the driver to properly generate the _id?

Here is a small example that demonstrates the problem.

public class MongoObject
{
    [BsonId(IdGenerator = typeof(StringObjectIdGenerator))]
    [BsonRepresentation(BsonType.ObjectId)]
    public string MongoID { get; set; }

    public int Index { get; set; }
}

var obj = new MongoObject()
{
    Index = 1
};

//This inserts the document, but with a _id set to Null
_collection.Update(Query.EQ("Index", BsonValue.Create(1)), Update.Replace(obj), UpdateFlags.Upsert, new WriteConcern() { Journal = true });

//This inserts the document with the expected autogenerated _id
//_collection.Insert(obj);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
313 views
Welcome To Ask or Share your Answers For Others

1 Answer

And of course I find the answer immediately after posting the question. From this answer, the solution is to add a [BsonIgnoreIfDefault] attribute to the ID. In the example from the question it would be:

public class MongoObject
{
    [BsonId(IdGenerator = typeof(StringObjectIdGenerator))]
    [BsonRepresentation(BsonType.ObjectId)]
    [BsonIgnoreIfDefault]    // <--- this is what was missing
    public string MongoID { get; set; }

    public int Index { get; set; }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...