MongoDB function to return a specific data/value?



To return a specific data, use findOne() in MongoDB. The findOne() method returns one document that satisfies the specified query criteria on the collection Let us create a collection with documents −

> db.demo473.insertOne( ... { ...    "_id" : new ObjectId(), ...    "Name" : "Chris", ...    "details" : { ...       "X-Coordinate" :10, ...       "Y-Coordinate" :15 ...    } ... } ... ); {    "acknowledged" : true,    "insertedId" : ObjectId("5e805a07b0f3fa88e227907d") } > db.demo473.insertOne( ... { ...    "_id" : new ObjectId(), ...    "Name" : "Bob", ...    "details" : { ...       "X-Coordinate" :11, ...       "Y-Coordinate" :12 ...    } ... } ... ); {    "acknowledged" : true,    "insertedId" : ObjectId("5e805a07b0f3fa88e227907e") }

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

> db.demo473.find();

This will produce the following output −

{ "_id" : ObjectId("5e805a07b0f3fa88e227907d"), "Name" : "Chris", "details" : { "X-Coordinate" : 10, "Y-Coordinate" : 15 } } { "_id" : ObjectId("5e805a07b0f3fa88e227907e"), "Name" : "Bob", "details" : { "X-Coordinate" : 11, "Y-Coordinate" : 12 } }

Following is the query to return a specific data with MongoDB findOne() function −

> db.demo473.findOne({ 'details.X-Coordinate':11 })

This will produce the following output −

{    "_id" : ObjectId("5e805a07b0f3fa88e227907e"),    "Name" : "Bob",    "details" : {       "X-Coordinate" : 11,       "Y-Coordinate" : 12    } }
Updated on: 2020-05-11T09:43:37+05:30

240 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements