MongoDB query by sub-field?


You can use dot(.) notation to query by subfield. Let us create a collection with a document. The query to create a collection with a document is as follows −

> db.queryBySubFieldDemo.insertOne(
   ... {
      ... "StudentPersonalDetails" : {"StudentName" : "John","StudentHobby" :"Photography"},
      ... "StudentScores" : {"MathScore" : 56}
   ... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c92c2995259fcd195499808")
}
> db.queryBySubFieldDemo.insertOne(
   ... {
      ... "StudentPersonalDetails" : {"StudentName" : "Chris","StudentHobby" :"Reading"},
      ... "StudentScores" : {"MathScore" : 97}
   ... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c92c2df5259fcd195499809")
}

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

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

The following is the output −

{
   "_id" : ObjectId("5c92c2995259fcd195499808"),
   "StudentPersonalDetails" : {
      "StudentName" : "John",
      "StudentHobby" : "Photography"
   },
   "StudentScores" : {
      "MathScore" : 56
   }
}
{
   "_id" : ObjectId("5c92c2df5259fcd195499809"),
   "StudentPersonalDetails" : {
      "StudentName" : "Chris",
      "StudentHobby" : "Reading"
   },
   "StudentScores" : {
      "MathScore" : 97
   }
}

Here is the query by subfield −

> db.queryBySubFieldDemo.find({"StudentPersonalDetails.StudentName":"Chris"}).pretty();

The following is the output −

{
   "_id" : ObjectId("5c92c2df5259fcd195499809"),
   "StudentPersonalDetails" : {
      "StudentName" : "Chris",
      "StudentHobby" : "Reading"
   },
   "StudentScores" : {
      "MathScore" : 97
   }
}

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements