Husker
Husker

Reputation: 61

Filter by last element in nested array in MongoDb

let's assume I have this object in mongo:

    {
      "_id": "1",
      "Test" {
        "Array": [ new NumberInt("10") ]
      }
    }

Now I would like to use this filter to check if last element in an array satisfy my condition:

    { "Test.Array.-1": { "$gte": new NumberInt("10") } }

But it doesn't work as I expected it to. Is it impossible to filter by last element in an array or do I do something wrong here?

Upvotes: 0

Views: 771

Answers (1)

ray
ray

Reputation: 15227

Chain up $gte with $arrayElemAt in a $expr

db.collection.find({
  $expr: {
    $gte: [
      {
        $arrayElemAt: [
          "$Test.Array",
          -1
        ]
      },
      10
    ]
  }
})

Mongo Playground

Upvotes: 3

Related Questions