首页 > 解决方案 > 您如何在 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'}
}]
});

标签: mongodbmongoose

解决方案


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

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

推荐阅读