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

MongoDBDatabaseBig Data Analytics

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 } } }
raja
Published on 02-Apr-2020 11:44:51
Advertisements