0

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.

2
  • Can you provide a sample database documents pls Commented Dec 12, 2021 at 22:44
  • and is there a reason for your product_price to be an array? u only have one object in it? Commented Dec 12, 2021 at 22:53

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Yeah. In resulted array we have only one object in it. It’s ok to remove the array
Thanks. it works for me

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.