首页 > 解决方案 > 如何在 mongodb 中创建嵌套查找?

问题描述

我想加入 3 张桌子。这是我的汇总,它只是加入第一个和第二个表。

 const products = await ProductInventory.aggregate([
    {
      $lookup: {
        from: 'productdetails',
        localField: 'prodId',
        foreignField: '_id',
        as: 'product',
      },
    },
    {
      $unwind: '$product',
    },
    {
      $match: { 'product.isActive': 'Yes' },
    },
  ]);

这是上面代码的结果。在产品中,我有一个类别及其类别的 ID。我也想在类别表中加入它。所以我可以得到类别名称。

"products": [
{
  "_id": "60a0e77b02a58f3038598301",
  "prodId": "TB-057",
  "stock_onhand": "30",
  "date_created": "2021-05-16T09:35:55.565Z",
  "date_updated": "2021-05-16T09:35:55.565Z",
  "__v": 0,
  "product": {
    "_id": "TB-057",
    "isActive": True,
    "product_name": "TEST2",
    "unit_price": "1.23",
    "markup_price": "1.23",
    "SRP": "2.46",
    "description": "test2",
    "category": "609521209d10ac4774748c74",
    "date_updated": "2021-05-16T09:35:55.562Z",
    "date_created": "2021-05-16T09:35:55.565Z",
    "__v": 0
  }
},

使用 $unwind: '$product' 后是否应该再次使用查找?

//SAMPLE DOCUMENTS
//This is the productinventories
 "_id" : ObjectId("609d398829be8e2bd8509d6e"),
    "prodId" : "TB-056",
    "stock_onhand" : "12",
    "date_created" : ISODate("2021-05-13T14:36:56.730Z"),
    "date_updated" : ISODate("2021-05-13T14:36:56.730Z"),
    "__v" : 0

//This is the productdetails
  "_id" : "TB-056",
    "isActive" : True,
    "product_name" : "TEST",
    "unit_price" : "1.23",
    "markup_price" : "1.23",
    "SRP" : "2.46",
    "description" : "maiba 1",
    "category" : ObjectId("609521209d10ac4774748c74"),
    "date_updated" : ISODate("2021-05-13T14:36:56.728Z"),
    "date_created" : ISODate("2021-05-13T14:36:56.730Z"),
    "__v" : 0

//this is the categories
 "_id" : ObjectId("609521209d10ac4774748c74"),
    "isActive" : True,
    "category_name" : "TABLET",
    "category_abbreviation" : "TB",
    "date_updated" : ISODate("2021-05-07T11:14:40.544Z"),
    "date_created" : ISODate("2021-05-07T11:14:40.544Z"),
    "__v" : 0

标签: node.jsmongodbmongooseaggregation-framework

解决方案


是的,$lookup如果您想从第三个集合中获取数据,您需要再次运行。

在你的情况下:

const products = await ProductInventory.aggregate([
  {
    $lookup: {
      from: 'productdetails',
      localField: 'prodId',
      foreignField: '_id',
      as: 'product',
    },
  },
  {
    $unwind: '$product',
  },
  {
    $match: { 'product.isActive': 'Yes' },
  },
  {
    $lookup: {
      from: 'categories',
      localField: 'product.category',
      foreignField: '_id',
      as: 'category',
    },
  },
  {
    $unwind: '$category',
  }
]);

推荐阅读