如何从猫鼬$ lookup集合中过滤结果

时间:2020-08-20 07:18:13

标签: node.js mongoose

我想在mongodb中过滤结果如下。我使用$ lookup填充另一个集合的结果。请检查我的以下代码
下面的代码是我得到的

 {
            "_id": "5f3d563122de0730d0f6a754",
            "barcode": "1234",
            "productname": "Lays Packet",
            "brandName": "Lays",
            "productSize": "12",
            "price": "12",
            "quant": "12",
            "imageurl": "http://localhost:3000/images/imageurl-1597855281050.jpg",
            "remaining": "12",
            "creator": "3d943b957fb5db510d824c5cbd6e8f7d",
            "__v": 0,
            "source": [
                {
                    "_id": "5f3a9bbc325a074240a1a815",
                    "firstname": "test",
                    "lastname": "test",
                    "storename": "test",
                    "gst": "test",
                    "phoneNumber": 1,
                    "email": "1@demo.com",
                    "address1": "test",
                    "address2": "test",
                    "city": "test",
                    "state": "test",
                    "country": "test",
                    "zip": "1",
                    "password": "1",
                    "usertype": 3,
                    "unique_SHOP": "3d943b957fb5db510d824c5cbd6e8f7d",
                    "__v": 0
                }
            ]
        },

如何仅从源代码列表中检索unique_SHOP和zip。我想要的结果如下所示,其中包含一个或多个字段

 {
    "_id": "5f3d563122de0730d0f6a754",
    "barcode": "1234",
    "productname": "Lays Packet",
    "brandName": "Lays",
    "productSize": "12",
    "price": "12",
    "quant": "12",
    "imageurl": "http://localhost:3000/images/imageurl-1597855281050.jpg",
    "remaining": "12",
    "creator": "3d943b957fb5db510d824c5cbd6e8f7d",
    "__v": 0,
    "source": [
        {
             "zip": "1",
            "unique_SHOP": "3d943b957fb5db510d824c5cbd6e8f7d",
            
        }
    ]
},

我使用的查询

   List.aggregate([
    {$match:
      { productname: { $regex: req.params.query,$options: "i" }}
    },
    { $lookup:{
          from: "suppliers",
          localField: "creator",
          foreignField: "unique_SHOP",
          as: "source"
        }
   },
  
  
  ]) 

1 个答案:

答案 0 :(得分:1)

您可以尝试$lookup with pipeline

    $match
  • creator id条件
  • $project以显示必填字段
  {
    $lookup: {
      from: "suppliers",
      as: "source",
      let: { creator: "$creator" },
      pipeline: [
        {
          $match: {
            $expr: { $eq: ["$$creator", "$_id"] }
          }
        },
        {
          $project: {
            _id: 0,
            zip: 1,
            unique_SHOP: 1
          }
        }
      ]
    }
  }

Playground