C#.NET – MongoDB Find Empty field in the document

CNET MongoDB Find Empty field in the document

Today in the article we shall learn how to use query using C#.NET – MongoDB Find Empty Field In The Document for the given collection. We shall verify queries using MongoShell or UI tools like a Compass UI.

We shall also see a C# MongoDB query to get all documents where the fields are empty in the mongo collection.

Today in this article, we will cover below aspects,

We shall also see a C# MongoDB query to get all the records fields that are not empty.

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.

CNET MongoDB Find Empty field in the document

C# Mongo- Find documents when a field is Empty

The below query matches documents where State field is empty

Query Pattern

{ Field Name : { $eq : "" } }

Example Query

{ State : {$eq : "" } }

C# Mongo Query Pattern

var tempQuery = new BsonDocument
                 {
                     {"State" , new BsonDocument {

                      { "$eq", string.Empty }
                     }}
                 };

Alternatively, please use the below builder pattern to create a query,

Find Empty field mongodb c

Note:

In the above query $eq an aggregate query compares two values (support both value and type) and returns:

  • true when the values are matching
  • false when the values are not matching

Syntax

{ $eq: [ <expression1>, <expression2> ] }

C# Mongo- Find documents when a field is not Empty

Query Pattern

{ Field Name : { $ne: "" } }

Example Query

{ State : {$ne: "" } }

C# Mongo Query

The below query matches documents where the “State” field is empty or “”

var tempQuery = new BsonDocument
                 {
                     {"State" , new BsonDocument {

                      { "$ne", string.Empty }
                     }}
                 };


C mongo driver field is not Empty document mongoose

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.



Leave a Reply

Your email address will not be published. Required fields are marked *