[英]Get documents by several field values
I have an food
mongodb schema as follows: 我有一个food
mongodb模式,如下所示:
{
name: 'Pork meat',
category: 'Meat'
}
Exists several categories and many items which belong to a specific category. 存在几个类别和属于特定类别的许多项目。
I want to sort items by category like this: 我想按以下类别对项目进行排序:
{
category: 'Meat', items: [ITEMS_WHICH_BELONG_TO_THIS_CATEGORY]
},
{
category: 'Drink', items: [ITEMS_WHICH_BELONG_TO_THIS_CATEGORY]
},
{
category: 'Souce', items: [ITEMS_WHICH_BELONG_TO_THIS_CATEGORY]
}
I have this code: 我有以下代码:
const categories = await Food.find().distinct('category').exec()
const result = []
for (let i = 0; i < categories.length; i++) {
result.push({ category: categories[i], items: await Food.find({ category: categories[i] }).exec() })
}
This is good, but can I optimize this code? 很好,但是我可以优化此代码吗? Can I do this in one query? 我可以在一个查询中执行此操作吗?
You can optimize your loop by using map or forEach to do this 您可以使用map或forEach来优化循环
const result = categories.map((category) => {
return {
category,
items: await Food.find({ category: category }).exec()
}
})
Use Aggregation pipeline for grouping your Food
items based on Categories
: 使用汇总管道根据Categories
对Food
项进行分组:
Food.aggregate([{
$group : {
_id : "$category",
items : { $push : "$name"}
}
}],function(err, result){
//result will have food items grouped by category
})
See MongoDB Aggregation and $group for more information. 有关更多信息,请参见MongoDB Aggregation和$ group 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.