0

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?

1 Answer 1

3

Chain up $gte with $arrayElemAt in a $expr

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

Mongo Playground

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

2 Comments

You can also use $last, like this, which is the same, just a bit cleaner (in my opinion)
@nimrodserok Thanks for enlightening me with the usage of $last. I thought we are only allowed to use it in a $group lol

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.