过滤+ ElemMatch

时间:2016-07-08 02:36:04

标签: c# mongodb mongodb-query

我有这样的文件:

{ 
  "File" : "xxxxxxx.txt",
  "Content" : [
      {   "tag" : "Book",
          "name" : "TestBook1",
          "value" : "xxx"
      },
      {   "tag" : "Dept",
          "name" : "TestDept1",
          "value" : "yyy"
      },
      {   "tag" : "Employee", 
          "name" : "TestEmployee1",
          "value" : "zzz"
      }]
}

使用以下代码

var subFilter = Builders<BsonDocument>.Filter.Eq("tag", "Dept");
var filter = Builders<BsonDocument>.Filter.ElemMatch("Content", subFilter);
var result =
    collection.Find(filter)
        .Project(Builders<BsonDocument>.Projection.Exclude("_id").Include("Content.$"))
        .ToList();

我可以

{   
    "tag" : "Dept",
    "name" : "TestDept1",
    "value" : "yyy"
}

如果我还需要在File字段上进行过滤,该怎么办?

所以我的查询是这样的:

If File = "xxxxxx.txt" and Content.tag = "Dept"

1 个答案:

答案 0 :(得分:2)

使用驱动程序版本2.2.3.3

  var fdb = Builders<BsonDocument>.Filter;
  var pdb = Builders<BsonDocument>.Projection;
  var subFilter = fdb.Eq("tag", "Note");
  var filter = fdb.And (
      fdb.Eq("File","xxxxxxx.txt"), 
      fdb.ElemMatch("Content", subFilter));
  var result = _collection
      .Find(filter)
      .Project(pdb.Exclude("_id").Include("Content.$").Include("File"))
      .ToList();