Zorro
Zorro

Reputation: 39

find array of objects with only matched object in subarray mongoose?

I'm trying to get an array of objects with the matching id's and with only sub-array product_price object with matching attributes size and model?

      product_name: {
        type: String,
        required: true,
      },
      service_hourly_price: {
        type: Number,
        required: true
      },
      product_price: [{
        model:{
          type: String,
          enum:['Euro','Japanese']
        },
        size:{
          type: String,
          enum: ['S','M','L','XL']      
        },
        price:{
          type: Number,
          required: true,
        }
      }],
    

Trying to query like this:

ProductSchema.aggregate( [
    {$match: { _id: { 
      $in: _id.map(function(_id){ return new mongoose.Types.ObjectId(_id) })
    }}},
    { $match : { product_price : {model : 'Euro' , size: 'S'}}}
    ])

how can I achieve result like this:

products:{
  _id: new ObjectId("61b3ab3ceba5bc724d754929"),
  product_name: 'Basic Service',
  service_hourly_price: 25,
  product_price: [
    {
      _id: new ObjectId("61b3ab3ceba5bc724d75492a"),
      size: 'S',
      model: 'Euro',
      price: 100
    }
  ]
},
{
  _id: new ObjectId("61b3aa88eba5bc724d7548fb"),
  product_name: 'Horn',
  service_hourly_price: 5,
  product_price: [
    {
      _id: new ObjectId("61b3aa88eba5bc724d7548fc"),
      size: 'S',
      model: 'Euro',
      price: 110
    }
  ]
}

product_price must contain only one matching object in it.

Upvotes: 0

Views: 620

Answers (1)

Branchverse
Branchverse

Reputation: 1397

I am uncertain why your product_prize is an array with only one object, you could remove the array there, and thus remove the $unwind in the aggregation, but nontheless this works for you right now:

ProductSchema.aggregate( [
    {$match: { 
      _id: { 
      $in: _id.map(function(_id){ return new mongoose.Types.ObjectId(_id) })
    }}}, {
    '$unwind': {
      'path': '$product_price'
    }
  }, {
    '$match': {
      'product_price.model': 'Euro', 
      'product_price.size': 'S'
    }
  }
])

Here try it out

Here the proof with the mongo Compass: enter image description here

Upvotes: 1

Related Questions