MongoDB filter out certain array elements using aggregation and return an object

24 views Asked by At

I have the data structure in MongoDB below representing an order.

order_id: 1
customer name: Peter
items: [{id:1, name: Laptop, shop_id: 10, id:2, name: Router, shop_id: 2}]
customer:{key:val, key2:val2}
date: 21-04-2023
isDeleted: False

I have two interfaces one for the admin and one shop owner. On my admin panel, I want to display all ordered items without filtering. The code below gives me that:

Parse.Cloud.define('getOrderWithUser', async (req) => {

const { master, params, user, } = req

  const query = new Parse.Query('Order')

  query.include('customer')
  query.include('items')
  query.notEqualTo('isDeleted', true)

  return query.get(params.id, { useMasterKey: true })

})

However, for shop owners where I need to filter out the content of items e.g. only shop_id = 10. I use an aggregation pipeline and an unwind function as shown in the code below.

Parse.Cloud.define('getOrderWithUser', async (req) => {
  var pipeline = [
    {match: {
      objectId: {$eq: params.id},
      isDeleted: {$ne: true}
    }},        
  {unwind: "$items"},        
   {
     match: {'items.shop_id': 10}}
   }, 
   {group:{
     objectId: params.id, 
     data: { $first : "$$ROOT" },
     items: {$push : "$items"}
   }
   },
   { replaceRoot: { newRoot: "$data" }}
  ]
  const query = new Parse.Query('Order')
  query.include('customer')
  query.include('items')
  return query.aggregate(pipeline, { useMasterKey: true })

})

The problem is, the aggregation approach does not work it returns an array of objects [{}] instead of just an object {}. Maybe I am not approaching this properly, all I want is to filter out items in the array based on the user type (admin or shop owner).

0

There are 0 answers