在猫鼬中添加查找后在$ project中添加剩余文件

问题描述

我正在从Order模式中的_id执行$ lookup,并且按预期方式工作。但是在$project中,如何添加剩余密钥。我在下面添加了我的代码。

产品系列:

{
"_id": "54759eb3c090d83494e2d804","product_name": "sample product","image": "default.png","price": 55,"discount": 5,}

订单列表集合

   {
        "user_name": "sample1","product_list":[
        {
          "product_id": "54759eb3c090d83494e2d804"
          "quantity": 5
        }
        ]
    }

查找

[
      {
        from: 'product',localField: 'product_list.product_id',foreignField: '_id',as: 'product_list.product_id',model: 'ProductModel',},],

$ Project

{
      user_name: true,product_list: {
        $map: {
          input: '$product_list.product_id',as: 'product',in: {
            product_name: '$$product.product_name',}

当前结果:

{
    "user_name": "sample1","product_list":[
       "product_id":{
          "product_name": "sample product"
        }
     ]
}

在当前结果中,数量字段丢失。如何添加$project?预期结果如下所示

预期结果:

   {
      "user_name": "sample1","product_list":[
           {
               "product_id": {
                    "product_name": "sample product"
                }
               "quantity": 5
           }
         ]
   }

解决方法

您需要在$unwind之前执行$lookup,因为它不能直接在数组字段中工作,并且这里在$ project中不需要$ map,

db.order.aggregate([
  { $unwind: "$product_list" },
  {
    $lookup: {
      from: "product",as: "product_list.product_id",let: { product_id: "$product_list.product_id" },pipeline: [
        {
          $match: {
            $expr: { $eq: ["$$product_id","$_id"] }
          }
        },{
          $project: {
            _id: 0,product_name: 1
          }
        }
      ]
    }
  },
  • $unwind和路径product_list.product_id,因为您需要将其作为对象
  { $unwind: { path: "$product_list.product_id" } },
    通过_id
  • $group重新构建您的product_list数组
  {
    $group: {
      _id: "$_id",user_name: { $first: "$user_name" },product_list: { $push: "$product_list" }
    }
  }
])

Playground

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...