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
How to properly use 'exist' function in MongoDB like in SQL?\\n
To check for existence of a record, use findOne() in MongoDB. Let us first create a collection with documents −
> db.existsAlternateDemo.insertOne({"StudentName":"Chris"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e06d23f9e4dae213890ac5c")
}
> db.existsAlternateDemo.insertOne({"StudentName":"Chris","StudentAge":21});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e06d2559e4dae213890ac5d")
}
>db.existsAlternateDemo.insertOne({"StudentName":"Chris","StudentAge":22,"StudentCountryName":"US"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e06d2689e4dae213890ac5e")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.existsAlternateDemo.find();
This will produce the following output −
{ "_id" : ObjectId("5e06d23f9e4dae213890ac5c"), "StudentName" : "Chris" }
{ "_id" : ObjectId("5e06d2559e4dae213890ac5d"), "StudentName" : "Chris", "StudentAge" : 21 }
{ "_id" : ObjectId("5e06d2689e4dae213890ac5e"), "StudentName" : "Chris", "StudentAge" : 22, "StudentCountryName" : "US" }
Here is the query to properly use 'exist' function in MongoDB like in SQL i.e. findOne() −
> db.existsAlternateDemo.findOne({"StudentCountryName" : "US"});
This will produce the following output −
{
"_id" : ObjectId("5e06d2689e4dae213890ac5e"),
"StudentName" : "Chris",
"StudentAge" : 22,
"StudentCountryName" : "US"
}Advertisements