跳至主要內容
  • Hostloc 空間訪問刷分
  • 售賣場
  • 廣告位
  • 賣站?

4563博客

全新的繁體中文 WordPress 網站
  • 首頁
  • mongoose 聚合管道查询, list 中的子对象如何关联?
未分類
23 9 月 2020

mongoose 聚合管道查询, list 中的子对象如何关联?

mongoose 聚合管道查询, list 中的子对象如何关联?

資深大佬 : ideacco 0

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     } } 

大佬有話說 (7)

  • 資深大佬 : ScaredHeart

    先通过[$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 的话

  • 資深大佬 : wkzq

    ““
    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`加索引

  • 資深大佬 : wkzq

    回复不支持 md, 用这个吧
    https://gist.github.com/fefine/d5fd3d60688d05887316ae25322f50f5

  • 主 資深大佬 : ideacco

    @ScaredHeart 感谢回复

  • 主 資深大佬 : ideacco

    @wkzq 感谢您的回复,谢谢

  • 主 資深大佬 : ideacco

    @wkzq 感谢回复

  • 主 資深大佬 : ideacco

    @wkzq 兄弟你这太厉害了,感谢感谢,抱拳!!

文章導覽

上一篇文章
下一篇文章

AD

其他操作

  • 登入
  • 訂閱網站內容的資訊提供
  • 訂閱留言的資訊提供
  • WordPress.org 台灣繁體中文

51la

4563博客

全新的繁體中文 WordPress 網站
返回頂端
本站採用 WordPress 建置 | 佈景主題採用 GretaThemes 所設計的 Memory
4563博客
  • Hostloc 空間訪問刷分
  • 售賣場
  • 廣告位
  • 賣站?
在這裡新增小工具