Reputation: 1231
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"
}]
}
I can find the document by using:
var filter = Builders<BsonDocument>.Filter.Eq("Content.tag", "Dept");
var result = collection.Find(filter).ToList();
However, this returns the whole document. Is there any way to just get the JSON object ({"tag" : "Dept", "name" : "TestDept1"}
)?
What I'm trying to get is just the "value" property (in this case, it's "yyy"), instead of the whole document.
UPDATE:
Like Phani suggested, I was able to make this work 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();
Upvotes: 0
Views: 2084
Reputation: 108
You need to use the ElemMatch projection for this.
Shell query for this : db.testing.find({Content:{$elemMatch:{"tag":"Dept"}}},{"_id":0,"Content.$":1})
C# query will be
Find(x => x.Content.Any(p => p.tag == "Dept")).Project(Builders<BsonDocument>.Projection.Exclude("_id").Include("Content.$")).ToList();
Please check if this is working.
Upvotes: 2