如何在猫鼬的关联模式的2个字段上分组?

时间:2019-01-14 07:31:01

标签: mongodb mongoose

这是我的2种模式:

我有一堆分配给一周中不同日期的食谱,每个食谱都包含成分,该成分由IngredientObject,数量和单位组成。

我想弄清楚日期在值20190008和20190010之间的时间,这是按componentObject和unit分组的数量之和。

我认为我不需要填充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'}
}]
});

1 个答案:

答案 0 :(得分:0)

我认为这应该可以解决问题

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" }
    }
  },
]);