MST

星途 面试题库

面试题:MongoDB的$project操作符在嵌套文档数组中的应用

假设有一个集合`orders`,文档结构如下:{"order_id":1,"customer":"Bob","items":[{"product":"Product A","quantity":2,"price":10},{"product":"Product B","quantity":1,"price":15}]}。使用聚合管道中的$project操作符,创建一个新字段`total_price`,其值为每个订单中所有商品的总价(即每个`items`数组中`quantity` * `price`的总和),并只返回`order_id`和`total_price`字段,写出对应的聚合代码。
33.2万 热度难度
数据库MongoDB

知识考点

AI 面试

面试题答案

一键面试
[
    {
        "$project": {
            "order_id": 1,
            "total_price": {
                "$sum": {
                    "$map": {
                        "input": "$items",
                        "as": "item",
                        "in": {
                            "$multiply": ["$$item.quantity", "$$item.price"]
                        }
                    }
                }
            }
        }
    }
]