在汇总结果中添加其他信息

时间:2019-09-18 02:36:11

标签: python mongodb pymongo

下面是我正在尝试的示例,但我无法弄清楚addFields部分。

我想在$$ items的管道中添加匹配expr中的created_at和amount字段。目前,它会返回$$ items中的所有created_at

用户模型

class User(BaseModel):
__schema__ = DictField(dict(
    user_id=StringField(required=True),
    name=StringField(required=True),
    item_list=ListField(default=[])
))

class InventoryAggregateManipulator(Manipulator):
    def transform_outgoing(self, doc, model):
        cur = User.aggregate([
            {"$lookup": {
                "from": "item",
                "let": {"items": "$item_list"},
                "pipeline": [
                    {"$match": {"$expr": {"$in": ["$_id", "$$items.id"]}}},
                    {"$project": {"name": "$name", 'rate': "$rate", "payout": "$payout"}},
                    {"$addFields": {"last_run": "$$items.created_at"}}
                ],
                "as": "inventory"
            }},
            {"$match": {"_id": doc['_id']}}
        ])
        for doc in cur:
            return doc

示例收藏集:

[
    {
        "_id": 1,
        "name": "some_item",
        "rate": 60,
        "payout": 15
    },
    {
        "_id": 2,
        "name": "another_item",
        "rate": 30,
        "payout": 20
    }
]

示例用户:

{
    '_id': 1,
    'user_id': 1234,
    'name': 'user123',
    'item_list':[
            {
                "id": 1,
                "created_at": datetime,
                "amount": 3
            },
            {
                "id": 2,
                "created_at": datetime,
                "amount": 5
            }
    ]
}

预期结果

{
    'user_id': 1234,
    'name': 'user123',
    'item_list':[
            {
                "id": 1,
                "created_at": datetime,
                "amount": 3
            },
            {
                "id": 2,
                "created_at": datetime,
                "amount": 5
            }
    ],
    'inventory':[
        {
            "name": "some_item",
            "rate": 60,
            "payout": 15,
            "last_run": [datetime from item_list],
            "amount": [amount from item_list]
        },
        {
            "name": "another_item",
            "rate": 30,
            "payout": 20,
            "last_run": [datetime from item_list],
            "amount": [amount from item_list]
        }
    ]
}

0 个答案:

没有答案