MongoDB Aggregate Match with String char

37 Views Asked by At

My sample document is

[
  {
    "id": 1234,
    "close": "11100",
    "products": [
      {
        "productId": 111
      }
    ]
  },
  {
    "id": 1235,
    "close": "10101",
    "products": [
      {
        "productId": 111
      }
    ]
  }
]

I wanted to fetch the documents only if the 'close' field second char is 0

note: index of char is dynamic

expected output:

{
        "id": 1235,
        "close": "10101",
        "products": [
          {
            "productId": 111
          }
        ]
      }

is there any way to filter the documents in the match stage?

Here is a sample doc mongoplayground

I tried this aggregation in the $project stage, but I wanted to filter this in $match stage. Thanks

close: {
    $not: {
      $regex: {
        $substr: ["$close", 2, 1],

        regex: "[1]",
      },
    },
  }
2

There are 2 best solutions below

3
Yong Shun On BEST ANSWER

Work with $regex operator

^ - Starts with

. - Any character

This will match the document with the close field containing '0' in the second character.

db.collection.aggregate([
  {
    "$match": {
      close: {
        $regex: "^.0"
      }
    }
  }
])

Demo @ Mongo Playground

So if you are looking for a dynamic index position:

^.{index position -1}0

For example, if you are looking for a second character, your regex pattern will be: ^.{1}0.

0
nimrod serok On

One option is:

db.collection.aggregate([
  {$match: {$expr: {$eq: [{$substr: ["$close", inxOfWantedChar, 1]}, "0"]}}}
])

See How it works on the mongoDB playground