RT,使用 mongoose,有如下两个数据,我想把产品参数据表,对应的产品查询出来,我目前只会查询一级的,在 Array 里面包裹的数据就不知道怎么取出来了,看了一天的官网文档也没看明白……惭愧惭愧,求大神给指个道吧。
示例数据如下:
// 产品数据表 product
{
"uid": "5f460572f639b62baa839baa",
"productCounts": 17,
"productItems": [{
"is_variants": false,
"totalVariants": 1,
"id": 12345 "tetle": "苹果"
},
{
"is_variants": false,
"totalVariants": 1,
"id": 23456 "tetle": "西瓜"
},
{
"is_variants": false,
"totalVariants": 1,
"id": 56789 "tetle": "荔枝"
},
...
]
}
// 产品参数数据表 options
{
"uid": "5f460572f639b62baa839baa",
"pid":23456,
"ditch": "weixin",
"postcode": 518000,
"is_pay": true
}
我想要的数据如下
{
"is_variants": false,
"totalVariants": 1,
"id": 12345,
"tetle": "苹果",
"options": {
"uid": "5f460572f639b62baa839baa",
"pid": 23456,
"ditch": "weixin",
"postcode": 518000,
"is_pay": true
}
}
1
ScaredHeart 2020-09-22 10:53:56 +08:00 1
先通过[$unwind]( https://docs.mongodb.com/manual/reference/operator/aggregation/unwind/index.html)把数组中的元素拆分,[$project]( https://docs.mongodb.com/manual/reference/operator/aggregation/project/index.html)修剪下数据,对 uid 字段[$lookup]( https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/index.html)来关联 options 表(uid 是 objectId 的话
|
2
wkzq 2020-09-22 10:54:43 +08:00 1
````
db.getCollection('emotes').aggregate([ {$match: {"productItems.id": 23456}}, {$unwind: "$productItems"}, {$match: {"productItems.id": 23456}}, { $lookup: { from: "options", localField: "productItems.id", foreignField: "pid", as: "options" } }, {$unwind: "$options"}, { $project: { "is_variants": "$productItems.is_variants", "totalVariants": "$productItems.totalVariants", "id": "$productItems.id", "tetle": "$productItems.tetle", "options": 1 } } ]) ```` 需要给`productItems.id`加索引 |
3
wkzq 2020-09-22 10:59:27 +08:00 1
|
4
ideacco OP @ScaredHeart 感谢回复
|