notlkk
notlkk

Reputation: 1231

Filter + ElemMatch

I have a document like this:

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

With the following code

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

I can get

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

What should I do if I also need to filter on the File field?

So my query is something like:

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

Upvotes: 2

Views: 5665

Answers (1)

andrei.ciprian
andrei.ciprian

Reputation: 3025

With driver version 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();

Upvotes: 3

Related Questions