【问题标题】:Need to aggregate and return results based on document nested array需要基于文档嵌套数组聚合返回结果
【发布时间】:2022-01-13 00:56:32
【问题描述】:

我有以下文件:

{
  "_id": ObjectId("10..."),
  "ownerName": "Merchant 10",
  ...,
  "stores": [
    {
      "id": ObjectId("20..."),
      "storeName": "Store 20"
    }, 
    {
      "id": ObjectId("21..."),
      "storeName": "Store 21"
    }
  ]
},
{
  "_id": ObjectId("11..."),
  "ownerName": "Merchant 11",
  ...,
  "stores": [
    {
      "id": ObjectId("22..."),
      "storeName": "Store 22"
    }
  ]
}

是否可以通过聚合返回基于嵌套数组“stores”的分页结果,并最终得到以下结果:

{
  "_id": "20...",
  "ownerName": "Merchant 10",
  "storeName": "Store 20"
}, {
  "_id": "21...",
  "ownerName": "Merchant 10",
  "storeName": "Store 21"
}, {
  "_id": "22...",
  "ownerName": "Merchant 11",
  "storeName": "Store 22"
}, 

所以基本上,我希望能够分享所有者信息,但根据商店返回结果。

我尝试了另一种方法来处理商店文档,但由于我的具体要求,我最终得到了循环依赖。

谢谢

【问题讨论】:

    标签: mongodb mongoose aggregate


    【解决方案1】:

    stores 上使用unwind,您可以展平文档。之后,只需project您需要的字段:

    db.mycollection.aggregate( [
       { $unwind: "$stores" },
       { $project: { "ownerName": 1, "storeName": "$stores.storeName" } }
    ] )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-26
      • 1970-01-01
      • 2020-02-07
      • 2021-06-11
      • 2018-02-11
      • 2019-05-20
      • 2019-05-10
      相关资源
      最近更新 更多