MongoDB query to access an object in an array

MongoDBDatabaseBig Data Analytics

To access an object in an array, use dot notation. Let us create a collection with documents −

> db.demo299.insertOne(
...   {
...      "id":100,
...      "Name":"Robert",
...      "details":[
...         {
...            "SubjectName":["C++","Python"]
...         },
...         {
...            "SubjectName":["Spring","Hibernate"]
...         }
...      ]
...   }
...);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4d685a5d93261e4bc9ea4b")
}
>
>
> db.demo299.insertOne(
...   {
...      "id":101,
...      "Name":"Adam",
...      "details":[
...         {
...            "SubjectName":["Python","JSP"]
...         },
...         {
...            "SubjectName":["Servlet","Operating System"]
...         }
...      ]
...   }
...);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4d685b5d93261e4bc9ea4c")
}

Display all documents from a collection with the help of find() method −

> db.demo299.find();

This will produce the following output −

{
   "_id" : ObjectId("5e4d685a5d93261e4bc9ea4b"), "id" : 100, "Name" : "Robert", "details" : [
      { "SubjectName" : [ "C++", "Python" ] },
      { "SubjectName" : [ "Spring", "Hibernate" ] }
   ]
}
{
   "_id" : ObjectId("5e4d685b5d93261e4bc9ea4c"), "id" : 101, "Name" : "Adam", "details" : [
      { "SubjectName" : [ "Python", "JSP" ] }, { "SubjectName" : [ "Servlet", "Operating System" ] }
   ]
}

Following is the query to access an object in an array −

> db.demo299.find({"details.SubjectName":"Servlet"});

This will produce the following output −

{
   "_id" : ObjectId("5e4d685b5d93261e4bc9ea4c"), "id" : 101, "Name" : "Adam", "details" : [
      { "SubjectName" : [ "Python", "JSP" ] }, { "SubjectName" : [ "Servlet", "Operating System" ] }
   ] 
}
raja
Published on 01-Apr-2020 07:22:16
Advertisements