AnKing
AnKing

Reputation: 2174

Parse string value into integer during MongoDB find query

I need to be able to parse deeply nested string value to be able to find an amount greater than in my request query. I fount that $expr operator is supposed to help in that, but when i try to implement it it gives me

"message" : "unknown operator: $expr",

here is my code:

db.OrderAttributes.find({
    InfluencedAttributes: {$elemMatch: {
        LexisAttributes:{$elemMatch: {
            $expr: { $gt: [ {$toDouble: "$MyAttributes.MyField"}, 500]}
        }}
    }}
}

the value I'm trying to compare is here

InfluencedAttributes.0.LexisAttributes.0.MyAttributes.MyField = "20000"

trimmed version of the lookup document:

db.OrderAttributes.insertOne({
    "InfluencedAttributes" : [
        {
            "LexisAttributes" : [
                {
                    "MyAttributes" : {
                        "MyValue" : "20000"
                    }
                },
                {
                    ...
                },
                {
                    ...
                }
            ]
        }
    ]
}})

Upvotes: 1

Views: 377

Answers (1)

Haniel Baez
Haniel Baez

Reputation: 1680

The problem is that $expr is not a valid query for $elemMatch, but you still have two way to achive the desire result:

First option:

db.OrderAttributes.find({"$expr": { "$gt": [ { "$toDouble": "$InfluencedAttributes.0.LexisAttributes.0.MyAttributes.MyField"}, 500 ] } } );

Performance: COLLSCAN for a collection scan.

Second option:

db.OrderAttributes.find({ "InfluencedAttributes.0.LexisAttributes.0.MyAttributes.MyField": {$regex: /^([5-9]\d{2,}|\d{4,})/ } } );

Performance: IXSCAN for scanning index keys.

Upvotes: 1

Related Questions