通过id从mongodb版本2.4中删除子文档

时间:2015-12-06 07:43:34

标签: c# mongodb nested

这是我的文件

Post{
  "_id" : 1,
  "Code" : CSUUID("ba22a2a3-e6b5-4ce6-a3ad-20e5196cca46"),
  "Zip" : 123456,
  "Text" : "Hello",
  "Tags" : [{
      "_id" : 1,
      "Tag" : "Tag8"
    }, {
      "_id" : 2,
      "Tag" : "Tag9"
    }, {
      "_id" : 3,
      "Tag" : "Tag10"
    }]
}

我需要在c#中按ID删除其中一个'标签'。 例如:delete from post where tag.id = 2

2 个答案:

答案 0 :(得分:3)

  

MongoDB.Bson版本:2.0.1.27

     

MongoDB.Driver版本:2.2.0.262

     

MongoDB.Driver.Code版本:2.2.0.262

const int id = 1;
var pull = Builders<Post>.Update.PullFilter(x => x.Tags, a => a.Id == id);
var filter1 = Builders<Post>.Filter.And(Builders<Post>.Filter.Eq(a => a.Id, 1), Builders<Post>.Filter.ElemMatch(q => q.Tags, t => t.Id == id));
collection.UpdateOneAsync(filter1, pull);

答案 1 :(得分:0)

我找到了答案。

var pull = Update<Post>.Pull(x => x.Tags, builder => builder.EQ(q => q.Id, 2)).ToBsonDocument();
var filter1 = Builders<Post>.Filter.And(Builders<Post>.Filter.Eq(a => a.Id, 1),
              Builders<Post>.Filter.ElemMatch(q => q.Tags, t => t.Id == 2));
collection.UpdateOneAsync(filter1, pull);