MongoDB query to fetch a specific document rom documents with field value set using NumberInt()?


The NumberInt() is used to explicitly specify 32-bit integers. Let us create a collection with documents −

> db.demo357.insertOne(
...    {
...       "FirstName" : "Chris",
...       "Age" : 21,
...       "details" : {
...          "studentDetails" : {
...             "id" : NumberInt(101)
...          }
...       }
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e568fa6f8647eb59e5620c9")
}
> db.demo357.insertOne(
...    {
...       "FirstName" : "David",
...       "Age" : 23,
...       "details" : {
...          "studentDetails" : {
...             "id" : NumberInt(110)
...          }
...       }
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e568fbaf8647eb59e5620ca")
}

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

> db.demo357.find();

This will produce the following output −

{ "_id" : ObjectId("5e568fa6f8647eb59e5620c9"), "FirstName" : "Chris", "Age" : 21, "details" : { "studentDetails" : { id" : 101 } } }
{ "_id" : ObjectId("5e568fbaf8647eb59e5620ca"), "FirstName" : "David", "Age" : 23, "details" : { "studentDetails" : { "id" : 110 } } }

Here is the query to get specific document −

> db.demo357.find({"details.studentDetails.id":NumberInt(110)});

This will produce the following output −

{ "_id" : ObjectId("5e568fbaf8647eb59e5620ca"), "FirstName" : "David", "Age" : 23, "details" : { "studentDetails" : { "id" : 110 } } }

Updated on: 02-Apr-2020

199 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements