1

I have a collection with this data:

[
    {
        _id: "123",
        number: 10,
        users: [
            {
                amount: 20
            }
        ]
    },
    {
        _id: "456",
        number: 20,
        users: [
            {
                amount: 10
            }
        ]
    }
]

I need to find documents where users[0].amount is greater than or equal to number. I have the following Mongoose query:

Model.aggregate([
    {
        $match: {
            $expr: {
                $and: [
                    { $gte: ["$users.0.amount", "$number"] },
                    ...
                ]
            }
        }
    }
]);

However, this doesn't seem to be filtering the documents properly. I'm assuming $users.0.amount isn't the correct syntax. How can I fix this?

1 Answer 1

1

$expr requires Aggregation Framework's syntax so you have to use $arrayElemAt instead:

{  $gte: [ { $arrayElemAt: [  "$users.amount",  0] }, "$number" ] }

where users.amount is an array of numbers

MongoDB Playground

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

1 Comment

Thanks, this works, I'll accept the answer after the timer is up

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.