2016-07-08 65 views
2

我有一個這樣的文件:過濾器+ ElemMatch

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

+0

試試這個。 var andFilter = subFilter&filter var result = collection.Find(andFilter).Project(Builders .Projection.Exclude(「_ id」).include(「Content。$」)) .ToList(); – notionquest

+0

什麼驅動程序版本? – profesor79

回答

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();