C# Mongo c驱动程序更新Builder AddToSet不更新现有项
我正在尝试使用UpdateBuilder.AddToSet方法更新BsonDocument中的数组项。但是,该方法总是在更新现有项目的数组中插入项目的新副本 这是我的目标:C# Mongo c驱动程序更新Builder AddToSet不更新现有项,c#,arrays,mongodb,upsert,C#,Arrays,Mongodb,Upsert,我正在尝试使用UpdateBuilder.AddToSet方法更新BsonDocument中的数组项。但是,该方法总是在更新现有项目的数组中插入项目的新副本 这是我的目标: public class Document { [BsonRepresentation(BsonType.ObjectId)] public String _id { get; set; } [BsonIgnoreIfNull] public List&
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更新该项。您的代码将转换为like:{u-id:tevent._-id} 我认为你应该使用: var query=query.EQEvents.\u id,tevent.\u id 它应该转换为like:{Events.\u id:tevent.\u id} 您可以在github上找到C驱动程序源: