How to filter array in subdocument with MongoDB?


You can use aggregate and unwind the array list before applying match. To understand the above concept, let us create a collection with documents. The query to create a collection with document is as follows:

> db.filterArray.insertOne( { "L": [{ "N":1 }, { "N":2 } , { "N":3 }, { "N":4 }, { "N":5 } ]});

The following is visible after running the above query:

{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c6d63f2734e98fc0a434aeb")
}

Display document from a collection with the help of find() method. The query is as follows:

> db.filterArray.find().pretty();

The following is the output:

{
   "_id" : ObjectId("5c6d63f2734e98fc0a434aeb"),
   "L" : [
      {
         "N" : 1
      },
      {
         "N" : 2
      },
      {
         "N" : 3
      },
      {
         "N" : 4
      },
      {
         "N" : 5
      }
   ]
}

Here is the query to filter array in subdocument with MongoDB. We have used $gt to get the fields greater than 3:

> db.filterArray.aggregate({ $match:{_id:ObjectId("5c6d63f2734e98fc0a434aeb")}}, {
$unwind:'$L'}, {$match:{'L.N':{$gt:3}}},
{$group:{_id:'$_id',subDocument:{$push:'$L.N'}}}).pretty();

The following is the output:

{
   "_id" : ObjectId("5c6d63f2734e98fc0a434aeb"),
   "subDocument" : [
      4,
      5
   ]
}

Updated on: 30-Jul-2019

292 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements