![](/img/trans.png)
[英]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.