FreakinaBox
FreakinaBox

Reputation: 461

mongodb use $lte with $indexOfArray

for a collection with the model

{
    stack: [{mean: 3.5}]
}

how can I make this query for the index of the stack array with a mean of less than 4.38?

db.stacks.aggregate([
    {
        $project: {
            index: { $indexOfArray: ['$stack', {mean: { $lte: 4.38 }}] },
        },
    },
]);

I am getting this error: {

    "ok" : 0,
    "errmsg" : "Expression $lte takes exactly 2 arguments. 1 were passed in.",
    "code" : 16020,
    "codeName" : "Location16020"
}

edit:

this doesn't give me an error but doesn't match anything either

db.mean.aggregate([
    {
        $project: {
            size: { $size: '$stack' },
            index: { $indexOfArray: ['$stack', {$lte: ['$mean', 4.38] } ] },
        },
    },
])

Upvotes: 5

Views: 921

Answers (1)

mickl
mickl

Reputation: 49945

You can run $map on every element of stack to get boolean values and then run $indexOfArray to get the index of first true value. You will get -1 if there's no matching element, try:

db.col.aggregate([
    {
        $project: {
            index: {
                $indexOfArray: [
                    { $map: { input: "$stack", in: { $lt: [ "$$this.mean", 4.0 ] } } },
                    true
                ]
            }
        }
    }
])

Upvotes: 5

Related Questions