Querying array elements with MongoDB?


MongoDB is better when you are querying array elements. Let us use the following syntax for querying array elements −

db.yourCollectionName.find({yourArrayFieldName:"yourValue"}).pretty();

The above syntax will return all those documents which have the value “yourValue” in an array field.

To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows −

> db.queryArrayElementsDemo.insertOne({
   ... "StudentName":"John","StudentFavouriteSubject":["C","Java"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c90c0354afe5c1d2279d694")
}
> db.queryArrayElementsDemo.insertOne({ "StudentName":"Carol","StudentFavouriteSubject":["C","C++"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c90c0434afe5c1d2279d695")
}
> db.queryArrayElementsDemo.insertOne({ "StudentName":"David","StudentFavouriteSubject":["MongoDB","Java"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c90c0584afe5c1d2279d696")
}

Display all documents from a collection with the help of find() method. The query is as follows −

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

The following is the output −

{
   "_id" : ObjectId("5c90c0354afe5c1d2279d694"),
   "StudentName" : "John",
   "StudentFavouriteSubject" : [
      "C",
      "Java"
   ]
}
{
   "_id" : ObjectId("5c90c0434afe5c1d2279d695"),
   "StudentName" : "Carol",
   "StudentFavouriteSubject" : [
      "C",
      "C++"
   ]
}
{
   "_id" : ObjectId("5c90c0584afe5c1d2279d696"),
   "StudentName" : "David",
   "StudentFavouriteSubject" : [
      "MongoDB",
      "Java"
   ]
}

Querying array elements with MongoDB −

> db.queryArrayElementsDemo.find({StudentFavouriteSubject:"Java"}).pretty();

The following is the output −

{
   "_id" : ObjectId("5c90c0354afe5c1d2279d694"),
   "StudentName" : "John",
   "StudentFavouriteSubject" : [
      "C",
      "Java"
   ]
}
{
   "_id" : ObjectId("5c90c0584afe5c1d2279d696"),
   "StudentName" : "David",
   "StudentFavouriteSubject" : [
      "MongoDB",
      "Java"
   ]
}

Look at the above sample output, the above query returns all those documents with the value “Java”.

Updated on: 30-Jul-2019

181 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements