MongoDB

mongodb $anyElementTrue $allElementsTrue

The $anyElementTrue and $allElementsTrue are the aggregation pipeline operators of MongoDB. The MongoDB $anyElementTrue operator only needs one expression as a parameter as a set that gives true if any of the elements provided to the set evaluates to be true. The same is the case with the $allElementsTrue operator. If any of the array’s elements are true when an array is evaluated as a group, MongoDB’s $anyElementTrue operator returns true. Moreover, the $anyElementTrue and $allElementsTrue operator analyzes all other elements as true, including arrays and non-zero integer values.

How Can We Use the $anyElementTrue and the $allElementsTrue Operator in MongoDB?

The usage of the $anyElementTrue and the $allElementsTrue operator is demonstrated here with the example implementation in the MongoDB shell. Firstly, we are required to define a collection that contains documents for the implementation of the $anyElementTrue and the $allElementsTrue operator. Here, we have represented the MongoDB collection “BlogPost” which is going to be used in this article. The collection “BlogPost” contains several documents which are first queried with the insertMany() method. With the insertMany() method, we have inserted the following document where the “_id” column indicates the serial number and the “Comments” is the array column specified with the different elements.

db.BlogPost.insertMany([
      {
          "_id": 1,
          "Comments" : [true, false]
},
       {
          "_id": 2,
          "Comments" : [1, true, 5]
      },
       {
          "_id": 3,
          "Comments" : [null, false, undefined, 0]
      },
   {
          "_id": 4,
          "Comments" : [true, [true]]
      },
  {
          "_id": 5,
          "Comments" : []
      }

  ])

The confirmation output successfully added the documents in the MongoDB “BlogPost” collection is displayed as follows:

{

 acknowledged: true,

 insertedIds: { '0': 1, '1': 2, '2': 3, '3': 4, '4': 5 }

}

Example # 1: Using the $anyElementTrue Operator in MongoDB

Here, we have utilized the $anyElementTrue operator of MongoDB which is set with a single argument expression. We have the aggregate() method where the $project operator is defined. The $project operator is further defined with the field “isAnyElementTrue” which employs the $anyElementTrue operator. The $anyElementTrue operator is applied with the single expression “[ “$Comments” ]”. The $anyElementTrue operator determines the value from the array field “$comments” that evaluates the true results.

db.BlogPost.aggregate([

    { $project: { "Comments": 1, isAnyElementTrue: { $anyElementTrue: [ "$Comments" ] } } }

] );

The $anyElementTrue operator will return the following result after executing the above query. It listed all the results to evaluate the true values against each document.

[

 { _id: 1, Comments: [ true, false ], isAnyElementTrue: true },

 { _id: 2, Comments: [ 1, true, 5 ], isAnyElementTrue: true },

 {  _id: 3, Comments: [ null, false, null, 0], isAnyElementTrue: false},

 { _id: 4, Comments: [ true, [ true ] ], isAnyElementTrue: true },

 { _id: 5, Comments: [], isAnyElementTrue: false }

]

Example # 2: Using the $anyElementTrue Operator in MongoDB Where No Value is True

When the documents do not contain any true value in the array field then the $anyElementTrue operator evaluates the false value. Let us have the example implementation of the $anyElementTrue operator where there is no true element in the array. Firstly, we have an aggregate() method where the $match operator is set with the condition “{ _id: 3 }” to be matched. Then, we have set the $project command where the “_id” field is excluded from the output as the value assigned to it is “0”. Next, we have defined a $anyElementTrue operator inside the $project operator variable “isAnyElementTrue”. We have input the expression “[$comments]” to the $anyElementTrue operator that will evaluate the expected results of the specified document.

db.BlogPost.aggregate(
  [
    { $match: { _id: 3 } },
    { $project: {
      _id: 0,
      isAnyElementTrue: { $anyElementTrue: [ "$Comments" ] } }
        }
  ]
)

The results showed the false value in the output because the document “_id:3” contained the array elements “[null, false, undefined, 0]” where no value is true. The $anyElementTrue operator always evaluates to false when array values are set as false, null, undefined, or 0.

[ { isAnyElementTrue: false } ]

Example # 3: Using the $anyElementTrue Operator in MongoDB for the Nested Array

The array is checked at the topmost level by the $anyElementTrue operator. Therefore, the $anyElementTrue operation does not descend the nested arrays. The nested array value either true or false is not affected by the $anyElementTrue operator. The nested array is considered as the element and $anyElementTrue indicates that it is true in this case. Just consider the $anyElementTrue operator query for the document which has the nested array. We have given a condition “{_id: { $in: [4] }}” to a $match operator. When the document whose “_id” is equal to “4” is found then the $anyElementTrue operator will figure out if the field “$Comments” evaluates the value “true”.

db.BlogPost.aggregate(
  [
    { $match: {_id: { $in: [4] }} },
    { $project: {
      isAnyElementTrue: { $anyElementTrue: [ "$Comments" ] } }
        }
  ]
)

For the aforementioned query, the outcomes are shown.

[ { _id: 4, isAnyElementTrue: true } ]

Example # 4: Using the $allElementsTrue Operator in MongoDB

Now, we have an example of another MongoDB operator “$allElementsTrue”. $allElementsTrue operator gives a true output value when there are no false values inside the array of the document. We can see the query of the $allElementsTrue is almost the same as for the $anyElementTrue. Here, we specified that the $allElementsTrue operator is the variable “isAllElementTrue” of the $project operator. Then, the “$allElementsTrue” operator contained the expression where the field “$Comments” is defined to evaluate the results.

db.BlogPost.aggregate([

  { $project: { "Comments": 1,"_id": 0, isAllElementTrue: { $allElementsTrue: [ "$Comments" ] } } }

] );

The output is listed with the array “comments” field values and the results against each document returned from the $allElementsTrue operator. We can generalize that the true value is obtained only from those documents which have no false values.

[

 { Comments: [ true, false ], isAllElementTrue: false },

 { Comments: [ 1, true, 5 ], isAllElementTrue: true },

 { Comments: [ null, false, null, 0 ], isAllElementTrue: false },

 { Comments: [ true, [ true ] ], isAllElementTrue: true },

 { Comments: [], isAllElementTrue: true }

]

Example # 5: Using the $allElementsTrue Operator in MongoDB Retrieves a False Value

The $allElementsTrue returns the false value when we have at least one false value in the array. Consider the query of the $allElementsTrue operator which returns the false value. Here, we have a $match operator defined with the expression “{ _id: 1 }” to match the document. After that, we have given a $project operator where the operator $allElementsTrue is called for the operation on the expression “[ “$Comments” ]”.

db.BlogPost.aggregate([
    { $match: { _id: 1 } },
    { $project: {
      _id: 0,
      isAllElementTrue: { $allElementsTrue: [ "$Comments" ] } }
        }]
)

We have the false output from the above query because there is one true array value and one false value in the array.

[ { isAllElementTrue: false } ]

Example # 6: Using the $allElementsTrue Operator in MongoDB on the Empty Array

The $allElementsTrue operator gives the true value in the case when the array has not been filled with any element. Here, we have provided the document whose array field is empty. Then, we applied the $allElementsTrue operator which takes the field “Comments” of that document to evaluate the expected outcome.

db.BlogPost.aggregate(
  [
    { $match: { _id: 5 } },
    { $project: {
      isAllElementTrue: { $allElementsTrue: [ "$Comments" ] } }
        }
  ]
)

The output generates the true value because the matched document contains an empty array.

[ { _id: 5, isAllElementTrue: true } ]

Conclusion

The MongoDB $anyElementTrue and $allElementsTrue operators are discussed in the article. We have explored the $anyElementTrue and $allElementsTrue operators with the basic and different cases. Firstly, we have explained the $allElementsTrue operator with the case when the array is not specified with the true value. Next, we have taken a case of the $anyElementTrue operator performing on the nested array. After that, we have $allElementsTrue where we first discuss when the false is obtained from this operator. Secondly, we have got the results of the $allElementTrue operator applied on the empty array.

About the author

Saeed Raza

Hello geeks! I am here to guide you about your tech-related issues. My expertise revolves around Linux, Databases & Programming. Additionally, I am practicing law in Pakistan. Cheers to all of you.