mongodb - 您如何在 mongoose 的关联模式上对 2 个字段进行分组?
问题描述
这是我的 2 个模式:
我有一堆分配给一周中不同日子的食谱,每个食谱都包含成分,由成分对象、数量和单位组成。
我想弄清楚日期在值 20190008 和 20190010 之间的位置,即按成分对象和单位分组的数量之和。
我认为我不需要填充成分对象,但我认为解决方案涉及填充配方,并且它们能够以某种方式对相关对象上的字段进行分组。我已经做了很多搜索,但不知道如何做到这一点。我可以在 SQL 中轻松做到这一点,但 Mongo / Mongoose 让我陷入了循环。帮助将不胜感激。
var daySchema = new mongoose.Schema({
date: DateOnly,
day: Number,
recipes: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Recipe"
}
],
usedBy: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
}
});
var recipeSchema = new mongoose.Schema({
name: String,
tag: [String],
createdBy: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
usedBy: [{
type: mongoose.Schema.Types.ObjectId,
ref: "User"
}],
ingredients: [{
ingredientObject: ingredientObjectSchema,
quantity: {type: Number, default: 1},
unit: {type: String, default: 'unit'}
}]
});
解决方案
我认为这应该可以解决问题
Day.aggregate([
// first you need to find days which are between 20190008 and 20190010
{
$match: {
'$and': [{ 'date': { $gte: 20190008 } }, { 'date': { $lte: 20190010 } }]
}
},
// now get recipes from the recipes table according to the ids in the recipes key
{
$lookup:
{
from: 'recipes', // apparently mongoose pluralises the table names
localField: 'recipes',
foreignField: '_id',
as: 'recipes_data'
}
},
// All the recipes are stored in the recipes_data object, but they are arrays instead of simple objects, so we'll unwind them
{
$unwind: '$recipes_data'
},
// Again since ingredients is an array, we'll unwind that as well and make individual objects as each document
{
$unwind: '$recipes_data.ingredients'
},
// Now we can group by ingredientObject and unit
{
$group: {
_id: { "ingredientObject": "$recipes_data.ingredients.ingredientObject", "unit": "$recipes_data.ingredients.unit" },
quantity: { $sum: "$recipes_data.ingredients.quantity" }
}
},
]);
推荐阅读
- reactjs - React Route v4 和 PrivateRoute 给出错误 - React.createElement: type is invalid
- asp.net-mvc - 在 ASP.NET MVC 5 应用程序中,如果用户尝试在未登录的情况下访问安全页面,如何强制用户登录
- php - (PHP) Ixudra/Curl 无法发布文件
- sql - 将两个sql行合二为一
- python - 何使用芹菜工人
- angular - 如何使可观察的 debounceTime 有条件
- javascript - 单独预览多个上传的图像
- django - django 内置 password_reset 从 send_email 更改连接
- python - Scrapy下一页链接没有给出任何内容
- javascript - WordPress AJAX 不显示内容