Mongoose 按查找字段分组
Posted
技术标签:
【中文标题】Mongoose 按查找字段分组【英文标题】:Mongoose group by lookup field 【发布时间】:2018-02-03 12:46:41 【问题描述】:我是 NodeJS 和 Mongoose 的新手,我正在尝试做一些高级查询。
我有三个文档(类别、子类别和产品)
Category.js
var mongoose = require('mongoose');
var CategorySchema = new mongoose.Schema(
name: type: String, required: true
);
mongoose.model('Category', CategorySchema);
module.exports = mongoose.model('Category');
Subcategory.js
var mongoose = require('mongoose');
var SubcategorySchema = new mongoose.Schema(
name: type: String, required: true ,
image: type: Buffer, contentType: String ,
idcategory: type: mongoose.Schema.Types.ObjectId, ref: 'Category'
);
mongoose.model('Subcategory', SubcategorySchema);
module.exports = mongoose.model('Subcategory');
Product.js
var mongoose = require('mongoose');
var ProductSchema = new mongoose.Schema(
name: type: String, required: true ,
idsubcategory: type: mongoose.Schema.Types.ObjectId, ref: 'Subcategory', required: true ,
price: type: Number, required: true
);
mongoose.model('Product', ProductSchema);
module.exports = mongoose.model('Product');
因此,产品有一个子类别,子类别具有一个类别。 由于我有这种结构,我想按类别计算我的产品。例如
[
"categoryName": "cat1": quantity: 10 ,
"categoryName": "cat2": quantity: 5 ,
"categoryName": "cat3": quantity: 2
]
我已经尝试了 $lookup 与 $group 没有成功,因为我根本不了解聚合。
猫鼬:“4.11.6”
【问题讨论】:
【参考方案1】:试试这个
CategoryModel.aggregate([
// stage 1: join subcategories
$lookup:
from: 'subcategories', // collection to join
localField: '_id', // field from categories collection
foreignField: 'idcategory', // field from subcategories collection
as: 'subcategory'
,
// at this point, each document will have an additional subcategory array with all the "joined" documents from subcategories collection
// stage 2: we need to "unwind" the subcategory array in order to join the products
// when you unwind an array, it's like making each element in the array have its own document
$unwind: '$subcategory'
,
// stage 3: join products
$lookup:
from: 'products', // collection to join
localField: 'subcategory._id', // field from our updated collection
foreignField: 'idsubcategory', // field from products collection
as: 'products'
,
// EDIT
// stage 4: strip out all fields except _id, category name, and quantity (number of products)
$project:
name: true,
quantity: $size: '$products'
,
// stage 5: group by category ID
$group:
_id: '$_id', // group by category ID
categoryName: $first: '$name' , // get category name
quantity: $sum: '$quantity' , // sum the quantities
]).exec(...);
【讨论】:
非常感谢@mikey。但是这段代码有一个小问题。问题是$first。这个 $first 显示了具有 category.id 的第一个组。但是,当我有两个 subcategories 用于同一类别时,它就不起作用了。我尝试改用 $sum 但效果不佳。 @brunnogrillo 也许尝试翻转第 4 阶段和第 5 阶段。基本上,在第 3 阶段之后,我们将获得所需的所有必要信息。然后在第4阶段,取出相关字段,包括获取每个类别+子类别文档的数量。然后是第 5 阶段,按类别对数量求和。 实际上,经过您的编辑,它可以工作。谢谢@mickey,这很有帮助以上是关于Mongoose 按查找字段分组的主要内容,如果未能解决你的问题,请参考以下文章
Mongoose/Mongodb Aggregate - 对多个字段进行分组和平均