查询/查找以返回 BsonDocument 中的 JSON 对象
本文关键字:中的 JSON 对象 BsonDocument 返回 查找 查询 | 更新日期: 2023-09-27 17:55:19
我有这样的文档:
{ "File" : "xxxxxxx.txt",
"Content" : [
{ "tag" : "Book",
"name" : "TestBook1",
"value" : "xxx"
},
{ "tag" : "Dept",
"name" : "TestDept1",
"value" : "yyy"
},
{ "tag" : "Employee",
"name" : "TestEmployee1",
"value" : "zzz"
}]
}
我可以通过以下方式找到文档:
var filter = Builders<BsonDocument>.Filter.Eq("Content.tag", "Dept");
var result = collection.Find(filter).ToList();
但是,这将返回整个文档。有没有办法只获取 JSON 对象({"tag" : "Dept", "name" : "TestDept1"}
)?
我试图得到的只是"value"属性(在本例中为"yyy"),而不是整个文档。
更新:
就像 Phani 建议的那样,我能够使用以下代码完成这项工作:
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();
为此,您需要使用 ElemMatch 投影。
Shell query for this : db.testing.find({Content:{$elemMatch:{"tag":"Dept"}}},{"_id":0,"Content.$":1})
C# 查询将是
Find(x => x.Content.Any(p => p.tag == "Dept")).Project(Builders<BsonDocument>.Projection.Exclude("_id").Include("Content.$")).ToList();
请检查这是否有效。