How do you perform an AND query on an array in MongoDB?


To get the same result like AND in MongoDB, use the $all operator. Let us first create a collection with documents −

> db.andQueryDemo.insertOne({"StudentName":"Carol Taylor","FavouriteSubject":["C","Java","MongoDB","MySQL"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cc73e7a8f9e6ff3eb0ce433")
}
> db.andQueryDemo.insertOne({"StudentName":"David Miller","FavouriteSubject":["C++","Java","MongoDB","SQL Server"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cc73ea48f9e6ff3eb0ce434")
}
> db.andQueryDemo.insertOne({"StudentName":"Carol Taylor","FavouriteSubject":["Python","PL/SQL"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cc73ed38f9e6ff3eb0ce435")
}

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

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

This will produce the following output −

{
   "_id" : ObjectId("5cc73e7a8f9e6ff3eb0ce433"),
   "StudentName" : "Carol Taylor",
   "FavouriteSubject" : [
      "C",
      "Java",
      "MongoDB",
      "MySQL"
   ]
}
{
   "_id" : ObjectId("5cc73ea48f9e6ff3eb0ce434"),
   "StudentName" : "David Miller",
   "FavouriteSubject" : [
      "C++",
      "Java",
      "MongoDB",
      "SQL Server"
   ]
}
{
   "_id" : ObjectId("5cc73ed38f9e6ff3eb0ce435"),
   "StudentName" : "Carol Taylor",
   "FavouriteSubject" : [
      "Python",
      "PL/SQL"
   ]
}

Following is the query to do an AND query on an array in MongoDB with $all. Here, we are displaying the array with both “Java” and “MongoDB” as FavouriteSubject −

> db.andQueryDemo.find({FavouriteSubject:{$all:["Java","MongoDB"]}}).pretty();

This will produce the following output −

{
   "_id" : ObjectId("5cc73e7a8f9e6ff3eb0ce433"),
   "StudentName" : "Carol Taylor",
   "FavouriteSubject" : [
      "C",
      "Java",
      "MongoDB",
      "MySQL"
   ]
}
{
   "_id" : ObjectId("5cc73ea48f9e6ff3eb0ce434"),
   "StudentName" : "David Miller",
   "FavouriteSubject" : [
      "C++",
      "Java",
      "MongoDB",
      "SQL Server"
   ]
}

Updated on: 30-Jul-2019

85 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements