Is it possible to use MongoDB to query for entries that have a particular value in a field in an object in an array?


Yes, to query for a field in an object in the array with MongoDB, use the following syntax −

db.yourCollectionName.find({"yourOuterFieldName": { $elemMatch: { "yourInnerFieldName": "yourValue" } } } ).pretty();

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

> db.objectInAnArrayDemo.insertOne({ "StudentDetails": [{
   "StudentName": "John", "StudentMessage": "Hi"}, {"StudentName": "Larry", "StudentMessage": "Hello"}]})
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c92635d36de59bd9de06381")
}
> db.objectInAnArrayDemo.insertOne({ "StudentDetails": [{
   "StudentName": "Carol", "StudentMessage": "Hello"}, {"StudentName": "David", "StudentMessage": "Good Morning"}]})
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c92637936de59bd9de06382")
}

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

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

The following is the output −

{
   "_id" : ObjectId("5c92635d36de59bd9de06381"),
   "StudentDetails" : [
      {
         "StudentName" : "John",
         "StudentMessage" : "Hi"
      },
      {
         "StudentName" : "Larry",
         "StudentMessage" : "Hello"
      }
   ]
}
{
   "_id" : ObjectId("5c92637936de59bd9de06382"),
   "StudentDetails" : [
      {
         "StudentName" : "Carol",
         "StudentMessage" : "Hello"
      },
      {
         "StudentName" : "David",
         "StudentMessage" : "Good Morning"
      }
   ]
}

Here is the query for a field in an object in the array with MongoDB −

> db.objectInAnArrayDemo.find({"StudentDetails": { $elemMatch: { "StudentMessage": "Good Morning" } } } ).pretty();

The following is the output −

{
   "_id" : ObjectId("5c92637936de59bd9de06382"),
   "StudentDetails" : [
      {
         "StudentName" : "Carol",
         "StudentMessage" : "Hello"
      },
      {
         "StudentName" : "David",
         "StudentMessage" : "Good Morning"
      }
   ]
}

Updated on: 30-Jul-2019

42 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements