ravi
ravi

Reputation: 27

How to do case insensitive filtering in mongoose?

I just started working on MongoDB and below is my code. I need to ignore casing while filtering data how to do it?

db.collection.aggregate([

  {
    $project: {
      _id: 0,
      name: 1,
      data: {
        $filter: {
          input: "$data",
          as: "el",
          cond: {
            $in: [
              "$$el",
              [
                "Min", //need to ignore casing
                "max",
                "gg"
              ]
            ]
          }
        }
      }
    }
  }
])

Thanks in advance

Upvotes: 1

Views: 405

Answers (1)

Tunmise Ogunniyi
Tunmise Ogunniyi

Reputation: 2573

You can use the $toLower operator to convert the filter element to lowercase then ensure the array elements in the conditional expression are all in lowercase:

db.collection.aggregate([
  {
    $project: {
      _id: 0,
      name: 1,
      data: {
        $filter: {
          input: "$data",
          as: "el",
          cond: {
            $in: [
              // Convert the input element to lower case
              { "$toLower": "$$el" },
              // Ensue all the elements of the array below are in lower case
              [
                "min",
                "max",
                "gg"
              ]
            ]
          }
        }
      }
    }
  }
])

Upvotes: 1

Related Questions