Set filtering conditions for nested array in MongoDB


To set filtering conditions, use $filter and $cond in MongoDB aggregate(). The $filter selects a subset of an array to return based on the specified condition. Let us create a collection with documents −

> db.demo725.insertOne(
...    {
...
...       "details": {
...
...          "userMessages": [
...             {
...                "Messages": [
...                   { "Message": "Hello" },
...                   { "Message": "How" },
...                   { "Message": "are" }
...                ]
...
...             },
...             {
...                "Messages": [
...                   { "Message": "Good" },
...                   { "Message": "Bye" }
...
...                ]
...             },
...             {
...                "Messages": [
...                   { "Message": "Hello" },
...                   { "Message": "Bye" }
...
...                ]
...
...             }
...          ]
...       }
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5eab16cd43417811278f5893")
}

Display all documents from a collection with the help of find() method −

> db.demo725.find();

This will produce the following output −

{ "_id" : ObjectId("5eab16cd43417811278f5893"), "details" : { "userMessages" : [ { "Messages" : [ { "Message" : "Hello" }, { "Message" : "How" }, { "Message" : "are" } ] }, { "Messages" : [ { "Message" : "Good" }, { "Message" : "Bye" } ] }, { "Messages" : [ { "Message" : "Hello" }, { "Message" : "Bye" } ] } ] } }

Following is the query to set filtering conditions for nested array −

> db.demo725.aggregate([
...    {
...       $addFields: {
...          "details.userMessages": {
...             $filter: {
...                input: "$details.userMessages",
...                as: "out",
...                cond: {
...                   $anyElementTrue: {
...                      $map: {
...                         input: "$$out.Messages",
...                         in: { $gte: [ { $indexOfBytes: [ "$$this.Message", "Hello" ] }, 0 ] }
...                      }
...                   }
...                }
...             }
...          }
...       }
...    }
... ]).pretty()

This will produce the following output −

{
   "_id" : ObjectId("5eab16cd43417811278f5893"),
   "details" : {
      "userMessages" : [
         {
            "Messages" : [
               {
                  "Message" : "Hello"
               },
               {
                  "Message" : "How"
               },
               {
                  "Message" : "are"
               }
            ]
         },
         {
            "Messages" : [
               {
                  "Message" : "Hello"
               },
               {
                  "Message" : "Bye"
               }
            ]
         }
      ]
   }
}

Updated on: 15-May-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements