[英]How can I submit an array of item numbers to query a mongoDB collection and return all requested docs as array of objects?
[英]MongoDB query array of objects in collection
我有一个集合,在这个集合中,我有一个名为Degrees
的对象数组。
此数组包含键为{Uni:'',Level:'',Degree:''}
,我希望能够向参数对象添加查找具有level = 'BS'
的度数的任何文档的能力,例如,不管对象中的其他字段包含什么。
到目前为止我已经尝试过:
{
$elemMatch: {
$eq: {
Uni: {
$exists: true,
},
Level: "BS",
Degree: {
$exists: true
}
}
}
}
但它没有奏效,有什么建议吗?
$elemMatch运算符匹配包含至少一个元素匹配所有指定查询条件的数组字段的文档。
{ <field>: { $elemMatch: { <query1>, <query2>, ... } } }
我想这应该适合你:
db.collection.find({Degrees: {$elemMatch: {level:'BS'}}})
不要忘记用你的模型名称替换集合。 :)
在此处查看 $elemMatch 文档: mongoDb $elemMatch
您可以直接查询嵌入数组中文档的字段。
如果您的文件看起来像
{
_id:ObjectId("..."),
Name: "",
degrees: [
{Uni:"",
Level:"BS",
Degree:""}
]
}
您可以返回包含至少一个“BS”级别学位的所有文档
db.collection.find({"degrees.Level":"BS"})
如果我正确理解你,并假设你的收藏被称为degrees
,它应该很简单:
// From the mongo shell:
db.degrees.find({ Level: 'BS' });
// From javascript (assuming node's native driver):
db.collection('degrees').find({ Level: 'BS' });
如果您只对第一个结果感兴趣,那么您可以使用以下内容:
// From the mongo shell:
db.degrees.findOne({ Level: 'BS' });
// From javascript:
db.collection('degrees').findOne({ Level: 'BS' });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.