

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Implementing MongoDB $exists and $ne?
The $exists is used to check whethre a filed exists, whereas $ne is for not equal condition. Let us first create a collection with documents −
> db.existsDemo.insertOne({"Name":"Chris","Age":21}); { "acknowledged" : true, "insertedId" : ObjectId("5cd7c3916d78f205348bc650") } > db.existsDemo.insertOne({"Name":"","Age":null}); { "acknowledged" : true, "insertedId" : ObjectId("5cd7c39a6d78f205348bc651") } > db.existsDemo.insertOne({"Name":null,"Age":24}); { "acknowledged" : true, "insertedId" : ObjectId("5cd7c3a66d78f205348bc652") } > db.existsDemo.insertOne({"Age":23}); { "acknowledged" : true, "insertedId" : ObjectId("5cd7c3c36d78f205348bc653") }
Following is the query to display all documents from a collection with the help of find() method −
> db.existsDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cd7c3916d78f205348bc650"), "Name" : "Chris", "Age" : 21 } { "_id" : ObjectId("5cd7c39a6d78f205348bc651"), "Name" : "", "Age" : null } { "_id" : ObjectId("5cd7c3a66d78f205348bc652"), "Name" : null, "Age" : 24 } { "_id" : ObjectId("5cd7c3c36d78f205348bc653"), "Age" : 23 }
Following is the query to implement $exists operator −
> db.existsDemo.find({"$and":[ {"Name":{"$exists":true}}, {"Name":{"$ne": ""}}]});
This will produce the following output −
{ "_id" : ObjectId("5cd7c3916d78f205348bc650"), "Name" : "Chris", "Age" : 21 } { "_id" : ObjectId("5cd7c3a66d78f205348bc652"), "Name" : null, "Age" : 24 }
- Related Questions & Answers
- Implementing MongoDB map-reduce
- Implementing String Comparison in MongoDB?
- How to query MongoDB using the $ne operator?
- Check if MongoDB database exists?
- Check that Field Exists with MongoDB?
- Return True if a document exists in MongoDB?
- How to determine whether a field exists in MongoDB?
- How to find if element exists in document - MongoDB?
- Check if table exists in MySQL and display the warning if it exists?
- How to apply a condition only if field exists in MongoDB?
- Check if value exists for a field in a MongoDB document?
- Implementing Stacks in C#
- Implementing Photomosaics in Python
- Implementing Checksum Using Java
- Implementing tree structure in Sapui5 and restricting parent property
Advertisements