find from last element's(object) field in array of objects in mongoose

Viewed 184

How to find data conditionally with mongoose by checking state field last element of history array.

{
        "_id" : ObjectId("5ff4360b3a1119002a6b8e04"),
        "name" : "sample"
        "history" : [ 
            {
                "_id" : ObjectId("56b0402a92b2a18116bf51de"),
                "state" : "pending"
            }, 
            {
                "_id" : ObjectId("56b0402a92b2a18116bf51fn"),
                "state" : "completed"
            }
        ],

    }

I try with following,

collection.find({$expr: {$eq: [{"$arrayElemAt": ["stateHistory", -1]}, "completed"]}})

Is there way to do this using find function without using aggregation?

1 Answers

you can use $where

collection.find({
    $where: function(){
        return this.history[this.history.length-1].state === "completed"
    }
})
Related