首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在mongoose中,如何对关联模式上的2个字段进行分组?

在mongoose中,如何对关联模式上的2个字段进行分组?
EN

Stack Overflow用户
提问于 2019-01-14 15:31:01
回答 1查看 34关注 0票数 0

下面是我的两个模式:

我将一堆食谱分配到一周中的不同日期,每个食谱都包含配料,这些配料由ingredientObject、数量和单位组成。

我想找出date在值20190008和20190010之间的位置,该值是按ingredientObject和单位分组的数量总和。

我认为我不需要填充ingredientObject,但我认为解决方案涉及到填充配方,并且它们能够以某种方式对相关对象上的字段进行分组。我已经做了一堆搜索,但我不知道如何做这件事。在SQL中我可以很容易地做到这一点,但是Mongo / Mongoose让我陷入了困境。我们将非常感谢您的帮助。

代码语言:javascript
运行
复制
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'}
}]
});

EN

回答 1

Stack Overflow用户

发布于 2019-01-14 20:35:36

我想这个应该行得通

代码语言:javascript
运行
复制
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" }
    }
  },
]);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54177274

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档