Search code examples
mongoosenodesmongoose-schemamongoose-populate

i need to find objects from array of object which satisfy some condition


here is my mongoose code

var agentSchema = new Schema({
datejoined: Date,
,
product: [{
   
    fleet: String,
    payment: String,

}] }) i want to get object from array product which satisfy the condition payment equals done

Agent.find({ _id: id, product: { $elemMatch: { payment: 'Done' } } })

i have tried this way

Agent.findone({ _id: id}).select( product: { $elemMatch: { payment: 'Done' } } }))

the methods showing either one object or all the object irrespective of the condition


Solution

  •  Agent.aggregate([{ $match: { _id: ObjectId(id) } }, { $unwind: "$product" },
        {
            $match: { 'product.payment': "Done" },
        },
    
    ]).then(prod => {
    

    i was able to solve my own with this code