skip to Main Content

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

Answers


  1. One option is:

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

    See How it works on the mongoDB playground

    Login or Signup to reply.
  2. Work with $regex operator

    ^ – Starts with

    . – Any character

    * – Match the previous token with zero or unlimited times.

    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.*.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search