1

I'm using MongoDB and i have the following records:

{
    name: "a",
    status: [
        { age: 15, closed: true},
        { age: 38, closed: true},
        { age: 42, closed: false},
    ]
},
{
    name: "b",
    status: [
        { age: 29, closed: true},
        { age: 5, closed: false},
    ]
}

I want to check if the before last object in status has for example age = 29.
so for that i have this working query:

db.col.find({
    $expr: {
        $eq: [
            29,
            {
                $let: {
                    vars: { beforeLast: { $arrayElemAt: [ "$status", -2 ] } },
                    in: "$$beforeLast.age"
                }
            }
        ]
    }
})

but i want now to check for example if age contain a value like "2". i need to use regex expression. is there anyway to convert that query to use regex inside/instead $eq operator ?
PS: i don't want to use aggregation because i'm working with an old version.

2 Answers 2

1

You can use $indexOfCP to find sub string inside an string character

db.collection.find({
  "$expr": {
    "$ne": [
      {
        "$indexOfCP": [
          { "$toLower": {
            "$let": {
              "vars": {
                "beforeLast": {
                  "$arrayElemAt": [
                    "$status",
                    -2
                  ]
                }
              },
              "in": "$$beforeLast.age"
            }
          }},
          "2"
        ]
      },
      -1
    ]
  }
})
Sign up to request clarification or add additional context in comments.

5 Comments

is there anyway to make it "insensitive case" ?
How can you use case insensitive with the numerical fields?
i want to use the same login with a string field
I am not able to getting your point. Please ask a new question with some proper clarification.
I m just asking if there any possibility to use "/a/i" instead of "2".
0

Try with aggregation

db.collection.aggregate([
{
 $project:
  {
     last: { $arrayElemAt: [ "$status", -2 ] },
  }
},
{$addFields:{
  ageInString: { $substr: [ "$last.age", 0, 3 ] }
  }},
  {$match:{ageInString:{ $regex: '^2' }}}
])

Comments

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.