我有一份这样的文件:

{
  "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"

最佳答案

带驱动程序版本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();

关于c# - 过滤+ ElemMatch,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38258139/

10-17 02:44