[英]MongoDB query array of subdocuments
I have researched throughly before posting this question but I could not find an accurate solution.在发布这个问题之前,我已经进行了彻底的研究,但我找不到准确的解决方案。 I have the below structure我有以下结构
stname: "SC",
dob : "1985",
education {[
{name : Lancaster,
year : 2013},
{name : Manchester,
year : 2001,
grad : 2004},
{name : Gambia,
year : 2001,
grad : 2011}
]}
So I want to return only documents that have grad fields.所以我只想返回具有 grad 字段的文档。 So the last two documents should be returned.所以应该返回最后两个文件。
I tried the following queries but to no avail我尝试了以下查询但无济于事
db.applicants.find({"education" : { $elemMatch : {"grad" : {$exists : true}}}}, {"name":1, "education.grad" : 1}).pretty()
returns only the first match as shown below,the first document is empty仅返回第一个匹配项,如下所示,第一个文档为空
{
"_id" : ObjectId("574dd5fcbda73af19e361a3f"),
"name" : "SC",
"education" : [
{
},
{
"grad" : "2004"
},
{
"grad" : "2011"
}
]
}
Also the below query gives you similar results, that is an empty document where ever grad field is not available.此外,以下查询为您提供了类似的结果,即一个空文档,其中 grad 字段不可用。
db.applicants.find({"education.grad" : { $exists : true}}, {"education.grad" : {$exists : true}, "education.grad" : 1, name : 1 , dob : 1}).pretty()
UPDATE ANSWER:更新答案:
db.applicants.aggregate({$unwind: "$education"},
{$match: {"education.grad":{$exists: true}}},
{$project: {"education.name": 1, "education.grad": 1, "_id": 0}})
This will return two records, no empty documents.这将返回两条记录,没有空文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.