How to search documents through an integer array in MongoDB?


You can use $where operator for this. Let us first create a collection with documents −

>db.searchDocumentArrayIntegerDemo.insertOne({"StudentFirstName":"John","StudentScores":[45,78,89,90]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd2a219345990cee87fd88c")
}
>db.searchDocumentArrayIntegerDemo.insertOne({"StudentFirstName":"Larry","StudentScores":[45,43,34,33]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd2a22a345990cee87fd88d")
}
>db.searchDocumentArrayIntegerDemo.insertOne({"StudentFirstName":"Chris","StudentScores":[]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd2a23c345990cee87fd88e")
}
>db.searchDocumentArrayIntegerDemo.insertOne({"StudentFirstName":"David","StudentScores":[99]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd2a24d345990cee87fd88f")
}

Following is the query to display all documents from a collection with the help of find() method −

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

This will produce the following output −

{
   "_id" : ObjectId("5cd2a219345990cee87fd88c"),
   "StudentFirstName" : "John",
   "StudentScores" : [
      45,
      78,
      89,
      90
   ]
}
{
   "_id" : ObjectId("5cd2a22a345990cee87fd88d"),
   "StudentFirstName" : "Larry",
   "StudentScores" : [
      45,
      43,
      34,
      33
   ]
}
{
   "_id" : ObjectId("5cd2a23c345990cee87fd88e"),
   "StudentFirstName" : "Chris",
   "StudentScores" : [ ]
}
{
   "_id" : ObjectId("5cd2a24d345990cee87fd88f"),
   "StudentFirstName" : "David",
   "StudentScores" : [
      99
   ]
}

Case 1 − Query when array contains at least one value −

> db.searchDocumentArrayIntegerDemo.find({ $where: "this.StudentScores.length >= 1" } );

This will produce the following output −

{ "_id" : ObjectId("5cd2a219345990cee87fd88c"), "StudentFirstName" : "John", "StudentScores" : [ 45, 78, 89, 90 ] }
{ "_id" : ObjectId("5cd2a22a345990cee87fd88d"), "StudentFirstName" : "Larry", "StudentScores" : [ 45, 43, 34, 33 ] }
{ "_id" : ObjectId("5cd2a24d345990cee87fd88f"), "StudentFirstName" : "David", "StudentScores" : [ 99 ] }

Case 2 − Query when array contains a common value in all documents −

> db.searchDocumentArrayIntegerDemo.find({StudentScores: 45}, {StudentScores:1});

This will produce the following output −

{ "_id" : ObjectId("5cd2a219345990cee87fd88c"), "StudentScores" : [ 45, 78, 89, 90 ] }
{ "_id" : ObjectId("5cd2a22a345990cee87fd88d"), "StudentScores" : [ 45, 43, 34, 33 ] }

Updated on: 30-Jul-2019

216 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements