下面是我的两个模式:
我将一堆食谱分配到一周中的不同日期,每个食谱都包含配料,这些配料由ingredientObject、数量和单位组成。
我想找出date在值20190008和20190010之间的位置,该值是按ingredientObject和单位分组的数量总和。
我认为我不需要填充ingredientObject,但我认为解决方案涉及到填充配方,并且它们能够以某种方式对相关对象上的字段进行分组。我已经做了一堆搜索,但我不知道如何做这件事。在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'}
}]
});
发布于 2019-01-14 20:35:36
我想这个应该行得通
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" }
}
},
]);https://stackoverflow.com/questions/54177274
复制相似问题