我是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');
因此,产品有一个具有类别的子类别。 由于我有这种结构,我想按类别计算我的产品。 i.g。
[
{ "categoryName": "cat1": quantity: 10 },
{ "categoryName": "cat2": quantity: 5 },
{ "categoryName": "cat3": quantity: 2 }
]
我已经尝试使用 $ group $ lookup 但没有成功,因为我根本不理解聚合。
猫鼬:“4.11.6”
答案 0 :(得分: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(...);