本文介绍了如何从一个集合引用另一个集合的数据? Mongodb的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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
and replace the supplierId as supplierName from collection
[
{
"_id": "5b9d25064dcf2327b449ae1b",
"supplierExist": true,
"supplierName": "NBA World Wide",
"supplierStatus": "Available",
"supplierTimeStamp": "2018-09-15T15:28:06.971Z",
"__v": 0
}
]
推荐答案
要与两个表联接,必须确保两个字段(即localField
和foriegnField
)的类型都相同.
For making join with two table you have make sure that the type for both the fields i.e. localField
and foriegnField
should be the same.
或
使用mongodb 4.0 ,您可以使用"> $toObjectId
聚合
With mongodb 4.0 you can easily change the type of the String
to ObjectId
using $toObjectId
aggregation
productSchema.aggregate([
{ "$lookup": {
"from": "supplierSchema",
"let": { "supplierId": { "$toObjectId": "$supplierId" }},
"pipeline": [
{ "$match": { "$expr": { "$eq": ["$_id", "$$supplierId"] }}}
]
as: "supplier"
}}
])
这篇关于如何从一个集合引用另一个集合的数据? Mongodb的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!