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 find if element exists in document - MongoDB?
To find if element exists in a MongoDB document, use MongoDB $exists. Let us create a collection with documents −
> db.demo497.insertOne({"details":[{"Name":"Chris"},{"Name":"Bob"}]});{
"acknowledged" : true,
"insertedId" : ObjectId("5e84b3cfb0f3fa88e22790d1")
}
> db.demo497.insertOne({"details":[{"Name":"Carol"}]});{
"acknowledged" : true,
"insertedId" : ObjectId("5e84b3d9b0f3fa88e22790d2")
}
> db.demo497.insertOne({"details":[{}]});{
"acknowledged" : true,
"insertedId" : ObjectId("5e84b3e9b0f3fa88e22790d3")
}
Display all documents from a collection with the help of find() method −
> db.demo497.find();
This will produce the following output −
{ "_id" : ObjectId("5e84b3cfb0f3fa88e22790d1"), "details" : [ { "Name" : "Chris" }, { "Name" : "Bob" } ] }
{ "_id" : ObjectId("5e84b3d9b0f3fa88e22790d2"), "details" : [ { "Name" : "Carol" } ] }
{ "_id" : ObjectId("5e84b3e9b0f3fa88e22790d3"), "details" : [ { } ] }
Following is the query to find if element exists in a document −
> db.demo497.find({$or:[
... {"details.Name" : {$ne : "Carol"}},
... {details: {$exists: false}}
... ]
... });
This will produce the following output −
{ "_id" : ObjectId("5e84b3cfb0f3fa88e22790d1"), "details" : [ { "Name" : "Chris" }, { "Name" : "Bob" } ] }
{ "_id" : ObjectId("5e84b3e9b0f3fa88e22790d3"), "details" : [ { } ] }Advertisements