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

MongoDBDatabaseBig Data Analytics

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"
      }
   ]
}
raja
Published on 01-Apr-2019 11:38:44
Advertisements