用猫鼬填充后如何聚合 [英] how to aggregate after populate with mongoose

查看:75
本文介绍了用猫鼬填充后如何聚合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用猫鼬,在填充后进行聚合时遇到问题. 下面是一个示例.

I'm working with mongoose, and I have a problem in doing aggregate after populate. Belows are an example.

猫鼬模型有两个模式,monster和collection.

There are two mongoose model schema, monster and collection.

const monster = new Schema({
    name: { type: String },
    power: { type: Number },
    armor: { type: Number },
});

const collection = new Schema({
    _monster: { type: Schema.Types.ObjectId, ref: 'Monster' },
    addedPower: { type: Number },
    addedArmor: { type: Number },
});

如您所见,字段"_monster"是模式"collection"到模式"monster"的外键.

As you see, field '_monster' is foreign key of schema 'collection' to schema 'monster'.

我想使用如下所示的路径填充怪物"和收藏".

I want to populate 'monster' and 'collection' using this path like below.

Collection.find().populate('_monster')

我想像下面这样汇总此结果.

And I want to aggregate this result like below.

AboveResult.aggregate([
    {
        '$project': {
            'new_field': { 
                '$add': [ 
                     '$addedPower', '$addedArmor', '$_monster.power', '$_monster.armor' 
                ]
            }
        }
    }
]);

以上操作无效,但我认为它可以解释我想要的内容.答案将很感激.

Above doesn't work, but I think it would explain about what I want. Answer will be thanksful.

推荐答案

您可以使用 $lookup 作为填充的替代方法,这是在服务器上完成的:

You can use $lookup as an alternative for the populate and this is done on the server:

Collection.aggregate([
    {
        "$lookup": {
            "from": "monsters",
            "localField": "_monster",
            "foreignField": "_id",
            "as": "monster"
        }
    },
    { "$unwind": "$monster" },
    {
        "$project": {
            "name": "$monster.name",
            "power": "$monster.power",
            "armor": "$monster.armor",
            "addedPower": 1,
            "addedArmor": 1,
            'new_field': { 
                '$add': [ 
                    '$addedPower', 
                    '$addedArmor', 
                    '$monster.power', 
                    '$monster.armor' 
                ]
            }
        }
    }
]).exec(callback);

这篇关于用猫鼬填充后如何聚合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆