Help with aggregate store and its deals

Hello!

I have this query that lists all stores + all the deals along with it as an array called “deals”.

db.stores.aggregate([{$lookup: {from: "deals", localField: "_id", foreignField: "store", as: "deals"}}])

Would it be possible to create an aggregate where I only provide the slug for a store and it gives me the
whole store document + the array with all deals?

Store:

{
  "_id": {
    "$oid": "636525107e14050c705adca1"
  },
  "name": "Amazon",
  "slug": "amazon",
  "country": "usa"
}

Deals:

{
  "_id": {
    "$oid": "63652803358e6b86f8f88860"
  },
  "name": "Get free shipping",
  "type": "coupon",
  "code": "FREESHIP",
  "store": {
    "$oid": "636525107e14050c705adca1"
  }
}

{
  "_id": {
    "$oid": "41652803358e6b86f8f88811"
  },
  "name": "30% off all beds",
  "type": "campaign",
  "store": {
    "$oid": "636525107e14050c705adca1"
  }
}

Hi @David_N_A7 ,

If I understood correctly you just need to do a $match stage before the lookup:

db.stores.aggregate([{$match : {"slug'" : "amazon" }},{$lookup: {from: "deals", localField: "_id", foreignField: "store", as: "deals"}}])

Obviously index {slug : 1, _id : 1} on stores and {store : 1} on deals.

Thanks
Pavel

2 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.