Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
}
}Advertisements