【问题标题】:Mongoose group by lookup fieldMongoose 按查找字段分组
【发布时间】: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”

【问题讨论】:

    标签: node.js mongoose aggregate lookup


    【解决方案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,这很有帮助
    猜你喜欢
    • 2018-09-01
    • 2017-03-22
    • 2023-03-14
    • 2020-11-27
    • 1970-01-01
    • 2013-01-09
    • 2020-03-27
    • 2017-10-16
    • 1970-01-01
    相关资源
    最近更新 更多