如何从一个集合引用另一个集合的数据? Mongodb

时间:2018-09-20 06:21:48

标签: node.js mongodb express aggregation-framework

router.get('/productSelect', (req, res, next) =>{
    productSchema.aggregate([   
        { $lookup:
            {
                from: 'supplierSchema',
                localField: 'supplierId',
                foreignField: '_id',
                as: 'supplier'
            }
        }

    ], (err, productSchema) =>{
        if(err) res.json(err);
        else res.json(productSchema);
    });
});

我想从集合中获取数据

[
  {
    "_id": "5ba26ff33318b51e20a80fb3",
    "productExist": true,
    "productName": "Anything",
    "supplierId": "5b9d25064dcf2327b449ae1b",
    "brandId": "5b9d162a316e8d2660f26393",
    "categoryId": "5ba2509a6367372568b1ce6d",
    "productPrice": 222,
    "productQuantity": 320,
    "productMax": 3,
    "productMin": 4,
    "productTimeStamp": "2018-09-19T15:49:07.177Z",
    "__v": 0
  }
]

并从集合中将SupplierId替换为SupplierName

[
  {
    "_id": "5b9d25064dcf2327b449ae1b",
    "supplierExist": true,
    "supplierName": "NBA World Wide",
    "supplierStatus": "Available",
    "supplierTimeStamp": "2018-09-15T15:28:06.971Z",
    "__v": 0
  }
]

1 个答案:

答案 0 :(得分:2)

要与两个表进行联接,请确保两个字段的类型,即localFieldforiegnField应该相同。

使用mongodb 4.0 ,您可以使用$toObjectId聚合轻松地将String的类型更改为ObjectId

productSchema.aggregate([   
  { "$lookup": {
    "from": "supplierSchema",
    "let": { "supplierId": { "$toObjectId": "$supplierId" }},
    "pipeline": [
      { "$match": { "$expr": { "$eq": ["$_id", "$$supplierId"] }}}
    ]
    as: "supplier"
  }}
])