Home > Mobile >  Need to aggregate and return results based on document nested array
Need to aggregate and return results based on document nested array

Time:01-14

I have the following document:

{
  "_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"
    }
  ]
}

Is it possible with aggregate to return paginated results based on nested array "stores", and end up with the following result:

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

So basically, I would like to be able to share owner info but returning result based on stores.

I tried another way with a stores document but with my specific requirement, I ended up with a circular dependency.

Thanks

CodePudding user response:

Using unwind on stores you can flatten out the documents. After that, just project the fields you need:

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