首页 > 解决方案 > 如何在不使用 mongodb 删除原始属性的情况下使用聚合函数进行“查找”或“加入”

问题描述

我有这个来自 mongodb 的对象

{
        "shaufel_customer_union_id": 3,
        "_id": "5ea97ad7f186dc9bddd17293",
        "shaufel_customers": [
            {
                "_id": "5ea978745f21919cbf465405",
                "customer_id": "1",
                "percent": 100,
                "customer": "5ea97655f186dc9bddd17292"
            },
            {
                "_id": "5ea978745f21919cbf465405",
                "customer_id": "2",
                "percent": 50,
                "customer": "5ea97b1bf186dc9bddd17294"
            }
        ],
        "createdAt": "2020-04-29T12:52:04.602Z",
        "updatedAt": "2020-04-29T12:52:04.602Z",
        "__v": 0,
        "id": "5ea97ad7f186dc9bddd17293"
    }

我要做的是$lookup为每个对象的 shaufel_customers 内的客户提供服务,以便我正在做的事情

   const aggregate = await CustomerUnionCustomer.aggregate([
        {
            $lookup: {
                from: 'customers',
                localField: 'shaufel_customers.customer',
                foreignField: '_id',
                as: 'shaufel_customers',
            }
        },


    ])

现在这段代码的问题是它加入了客户的文档,但它删除了percent导致这个的属性

   {
        "_id": "5ea97ad7f186dc9bddd17293",
        "shaufel_customer_union_id": 3,
        "shaufel_customers": [
            {
                "_id": "5ea97655f186dc9bddd17292",
                "migration_customer_id": "3"
            },
            {
                "_id": "5ea97b1bf186dc9bddd17294",
                "migration_customer_id": "5"
            }
        ],
        "createdAt": "2020-04-29T12:52:04.602Z",
        "updatedAt": "2020-04-29T12:52:04.602Z",
        "__v": 0
    }

那么我应该如何加入客户文档并percent使用 mongodb 聚合函数保留属性。

标签: databasemongodbmongooseaggregation-frameworkaggregate

解决方案


推荐阅读