How can I find documents in MongoDB based on the number of matched objects within an array?

MongoDBDatabaseBig Data Analytics

Let us see an example and create a collection with documents −

> db.demo694.insertOne(
...    {
...       "details" :
...       [
...          {
...             "Name" : "Chris",
...             Age:21
...          },
...          {
...             "Name" : "David",
...             Age:22
...          }
...       ]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea59279ece4e5779399c07f")
}
> db.demo694.insertOne(
...    {
...       "details" :
...       [
...          {
...             "Name" : "Bob",
...             Age:21
...          },
...          {
...             "Name" : "Mike",
...             Age:23
...          }
...       ]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea5927aece4e5779399c080")
}
> db.demo694.insertOne(
...    {
...       "details" :
...       [
...          {
...             "Name" : "Chris",
...             Age:21
...          },
...          {
...             "Name" : "Carol",
...             Age:22
...          }
...       ]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea5927aece4e5779399c081")
}

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

> db.demo694.find();

This will produce the following output −

{ "_id" : ObjectId("5ea59279ece4e5779399c07f"), "details" : [ { "Name" : "Chris", "Age" : 21 }, { "Name" : "David", "Age" : 22 } ] }
{ "_id" : ObjectId("5ea5927aece4e5779399c080"), "details" : [ { "Name" : "Bob", "Age" : 21 }, { "Name" : "Mike", "Age" : 23 } ] }
{ "_id" : ObjectId("5ea5927aece4e5779399c081"), "details" : [ { "Name" : "Chris", "Age" : 21 }, { "Name" : "Carol", "Age" : 22 } ] }

Following is the query to find documents in MongoDB based on the number of matched objects within an array −

> nameChrisAge21= function () {
...    var inc = 0;
...    this.details.forEach(function (d) {
...       if (d.Name == "Chris" && d.Age == 21) {
...          inc= inc + 1;
...       }
...    });
...    if (inc >= 1) {
...       return true;
...    }
... }
function () {
   var inc = 0;
   this.details.forEach(function (d) {
      if (d.Name == "Chris" && d.Age == 21) {
         inc= inc + 1;
      }
   });
   if (inc >= 1) {
      return true;
   }
}
> db.demo694.find({$where:nameChrisAge21});

This will produce the following output −

{ "_id" : ObjectId("5ea59279ece4e5779399c07f"), "details" : [ { "Name" : "Chris", "Age" : 21 }, { "Name" : "David", "Age" : 22 } ] }
{ "_id" : ObjectId("5ea5927aece4e5779399c081"), "details" : [ { "Name" : "Chris", "Age" : 21 }, { "Name" : "Carol", "Age" : 22 } ] }
raja
Published on 14-May-2020 12:49:06
Advertisements