MongoDB find Empty Field in document
Today in the article we shall learn how to query documents when MongoDB Field is empty in a document in a collection.
We shall verify queries using MongoShell or UI tools like a Compass UI.
We shall also see a query to get all documents where the field is not empty in the mongo collection.
We shall also see all the records which are not empty as well.
We shall also be running the query using the .NET C# mongo driver. If interested to know how to run queries using .NET C# mongo driver please check this article.
Today in this article, we will cover below aspects,
Getting started
I have a sample MongoDB document as below in one of the collections. Here we shall be trying to search all the documents where the State field is empty.
Mongo- Find documents when field is Empty
The below query matches documents that where State field is empty
Query Pattern
{ Field Name : { $eq : "" } }
Example Query
{ State : {$eq : "" } }
Results:
Using Compass
Using Mongo shell
Below sample query using CLI/shell to get fields with empty records,
Note:
In the above query $eq
an aggregate query compares two values (support both value and type) and returns:
true
when the values are matchingfalse
when the values are not matching
Syntax
{ $eq: [ <expression1>, <expression2> ] }
Mongo- Find documents when field is not Empty
The below query matches documents that where State field is empty
Query Pattern
{ Field Name : { $ne: "" } }
Example Query
{ State : {$ne: "" } }
Results:
The field is null or Not Set in MongoDB
Please visit the below article for more details,
That’s all, So today we learned the simple mongo query for identifying the records where the field is null or not set. It’s pretty easy to prepare the query for such needs.
References:
Do you have any comments or ideas or any better suggestions to share?
Please sound off your comments below.
Happy Coding !!
Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.