| by Arround The Web | No comments

MongoDB $Filter Operator

The MongoDB $filter operator retrieves a subset of an array that is based on a predefined criterion. In another word, the $filter operator provides an array that only contains the elements that satisfy the criteria in the order that they were specified. The $filter operator has parameters that include the “input”, “as”, and “cond”. The “input” argument is the expression that takes the array field to filter the specified document. Next is the optional argument “as” which takes the variable name of the input array element to access each element. Then, the “cond” argument determines whether the element is included in the resultant array.

How the $Filter Operator Is Used in MongoDB

The $filter operator of MongoDB is used to filter out the array data according to the given conditional statement. The usage of the $filter operator works on the documents that are inserted in the specified collection of MongoDB. Here, we deploy the insertMany() query of MongoDB to insert three documents in the “Cricket” collection. Each record contains three fields – “_id”, “player” and the “runsRecord” – which are set as an array. The document inserting format is represented in the following:

db.Cricket.insertMany([{
        "_id" : 1,
        "player" : "Ravi",
        "runsRecord" :[100 , 50, 70],
       "Matches" :
          {
             "Match1" : "WorldCup",
             "Year":"2000"
          }
},
{
        "_id" : 2,
        "player" : "Andrew",
        "runsRecord" :[150 , 90, 55]
         
},
{
       "_id" : 3,
        "player" : "Smith",
        "runsRecord" :[80 , 99, 45]
},
{
       "_id" : 4,
        "player" : "Alex",
        "runsRecord" :[]
 }])

The documents in the “Cricket” collection are successfully inserted as shown in the following output:

{ acknowledged: true, insertedIds: { '0': 1, '1': 2, '2': 3, '3': 4 } }

Example 1: MongoDB Uses the $Filter Operator in MongoDB

The basic $filter operator of the MongoDB example is given in this section. We set a query where the $project operator is called in the aggregate method. We invoke the $filter operator within the $project operator. The $filter operator is further specified with its parameter. The “input” parameter is set with the name of the “$runsRecord” array field with the “$” sign to extract the data from it. Then, we use the “as” parameter to give the title to the return variable, “runsRecord”. This variable is then referred to using the “cond” parameter with the double dollar sign, “$$”. Next is the “Cond” parameter where the expression is assigned as “$gt: [ “$$runsRecord”, 50 ]”. The conditions imply that the “$gt” operator gets the array element which is greater than the value of “50” in the “runsRecord” array field.

db.Cricket.aggregate([
   {
      $project: {
         highRuns: {
            $filter: {
               input: "$runsRecord",
               as: "runsRecord",
               cond: { $gt: [ "$$runsRecord", 50 ] }
            }
         }
      }
   }
])

The results of the following $filter query return only those values from the array which is greater “50”. The value which is less than “50” is ignored by the $filter operator.

[
  { _id: 1, highRuns: [ 100, 70 ] },
  { _id: 2, highRuns: [ 150, 90, 55 ] },
  { _id: 3, highRuns: [ 80, 99 ] },
  { _id: 4, highRuns: [] }
]

Example 2: MongoDB Uses the $Filter Operator to Filter the Non-Existence Field

Now, we take a case where the $filter operator is applied to the field that is not present in any inserted collection documents. Here, we have a query where the $filter operator is employed with the parameters. The input parameter is set with the “$salary” field to filter the document. Then, we utilize the “as” optional parameter which is also given with the variable name, “salary”, which is used in the input array as an element. After this, we have a conditional expression in the “cond” parameter of the $filter. The $filter operator filters out the array element based on the specified condition which is “$gte: [ “$$salary”, 6000 ]”.

db.Cricket.aggregate([
  {
    $match: { _id: { $in: [ 2 ] } }
  },
  {
    $project: {
        highRuns: {
          $filter: {
              input: "$salary",
              as: "salary",
              cond: { $gte: [ "$$salary", 6000 ] }
          }
        }
    }
  }
])

As we know, the provided “salary” field is not present in the document whose “_id” is “2” so the output of the previous query of the $filter operator gives a null value.

[ { _id: 2, highRuns: null } ]

Example 3: MongoDB Uses the $Filter Operator to Filter the Empty Array

Next is the scenario where the $filter is employed over the empty array. The $filter operator returns an empty array set if one of the documents in the collection has an empty array. We have the following $filter operator query. We have the $match operator first where the “{ _id: { $in: [ 4 ] }” expression is provided to be satisfied. When the $in operator finds the value of “4” against the “_id” field, the next operator proceeds. Then, we have a $filter operator which filters the array of elements based on the given condition which is “{ $gt: [ “$$runsRecord”, 45 ] }”.

db.Cricket.aggregate([
  {
    $match: { _id: { $in: [ 4 ] } }
  },
  {
    $project: {
        highRuns: {
          $filter: {
              input: "$runsRecord",
              as: "runsRecord",
              cond: { $gt: [ "$$runsRecord", 45 ] }
          }
        }
    }
  }
])

The “_id:4” has the “runsRecord” array field which is empty. That is why when the query is executed, it outputs the empty array as follows:

[ { _id: 4, highRuns: [] } ]

Example 4: MongoDB Uses the $Filter Operator in MongoDB with the Optional Variable Name

We set a title to the variable in the preceding instances using the “as” argument. If the “as” argument is not set with any variable name, the “$this” variable is set by default by MongoDB. Let’s have the query example for this statement. We match the document by calling the $match operator where we have an “_id” field in which the values are set. We assign a $filter operator to the “$project” operator where the $filter operator is called with the parameters. Here, we have an “input” parameter with the name of the “$runsRecord” array field. Then, we apply the “cond” parameter with the specified condition. The condition is set as “cond: { $lt: [ “$$this”, 80 ]”. This time, the $lt operator is used to find the value which is less than the value of “80”. Note that instead of a “$$runsRecord” variable name, we use the “$$this” default variable name here which does not affect the resultant output.

db.Cricket.aggregate([
  {
    $match: { _id: { $in: [ 1, 2, 3, 4 ] } }
  },
  {
    $project: {
        highRuns: {
          $filter: {
              input: "$runsRecord",
              cond: { $lt: [ "$$this", 80 ] }
          }
        }
    }
  }
])

The $filter operator filters the specified array with the $this variable in the same way as with the specified variable.

[
  { _id: 1, highRuns: [ 50, 70 ] },
  { _id: 2, highRuns: [ 55 ] },
  { _id: 3, highRuns: [ 45 ] },
  { _id: 4, highRuns: [] }
]

Example 5: MongoDB Uses the $Filter Operator to Filter with Multiple Conditions

We can provide more than one condition to the $filter operator to filter out only those documents that match the given condition. Here, we define the $filter operator where the $and operator are used in the “cond” parameter. The $and operator is set with the multiple conditions like“{ $gte: [ “$$runsRecord”, 45 ]” and “{ $lte: [ “$$runsRecord”, 99 ] }”. The $and operator are used which require both conditions as true.

db.Cricket.aggregate([
   {
      $project: {
         highRuns: {
            $filter: {
               input: "$runsRecord",
               as: "runsRecord",
              cond: { $and: [
        { $gte: [ "$$runsRecord", 45 ] },
        { $lte: [ "$$runsRecord", 99 ] }
      ] }
            }
         }
      }
   }
])

With the multiple conditions, we filter out the matched document in the following:

[
  { _id: 1, highRuns: [ 50, 70 ] },
  { _id: 2, highRuns: [ 90, 55 ] },
  { _id: 3, highRuns: [ 80, 99, 45 ] },
  { _id: 4, highRuns: [] }
]

Conclusion

We explored this article which is about the $filter operator of MongoDB. Here, we provided the implementation of the MongoDB script of the $filter operator to filter the specified data. We first demonstrated the basic usage of the $filter operator. Then, we used the $filter operator over the document whose field is not added in the document. The empty array field case is also deployed on the $filter operator which retrieves the empty array. Furthermore, the $filter operator is used with the $this variable which is the default variable.

Share Button

Source: linuxhint.com

Leave a Reply