1

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

0

1 Answer 1

1

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" } }
] )
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.