2015-05-19 38 views
0

我想使用UpdateBuilder.AddToSet方法更新BsonDocument中的數組項目。但是,該方法始終將該項目的新副本插入到更新現有數據的陣列中。Mongo C#驅動程序UpdateBuilder AddToSet不更新現有項目

這是我的目標:

public class Document 
    { 
     [BsonRepresentation(BsonType.ObjectId)] 
     public String _id { get; set; } 
     [BsonIgnoreIfNull] 
     public List<Event> Events { get; set; } 
    } 

    public class Event 
    { 
     [BsonRepresentation(BsonType.ObjectId)] 
     public String _id { get; set; } 
     [BsonIgnoreIfNull] 
     public String Title { get; set; } 
    } 

這裏是我嘗試更新的陣列項目,是根據它的_id:

//tevent is an instance of an existing event, with just the Title changed 
    var update = new UpdateBuilder<Document>(); 
    update.AddToSet<Event>(t => t.Events, tevent); 
    var query = Query<Event>.EQ(t => t._id, tevent._id); 

    //GetCollection() return the document collection 
    var result = GetCollection().Update(query, update, UpdateFlags.Upsert); 

正如之前所說,項目被添加到陣列中,即使有一個具有相同_id的項目。如果已經存在於文檔數組中,我想用相同的_id更新該項目。

回答

相關問題