Element Operators

Overview

MongoDB providers two element query operators that helps you find documents based on a field's existence or type. In other words, you can match documents based on whether a field exists or in case it does exist, based on its type. The two element operators presented on this section are:

Operator

Description

Exists

Matches documents when the specified field exists

Type

Matches documents when a field is of the specified type

Exists operator - $exists

The $exists operator matches the documents that contain the specified field, even if its value is null.

Builders<T>.Filter
    .Exists(doc => doc.<field>, <true || false>)

The filter definition being created with the Existsmethod on a specific field, matches the documents which contain the field even if its value is null.

The sample uses the Exists operator to find Order documents that have assigned a lot number. The LotNumber is a nullable int property in the Orderclass.

ElementOperators.cs
var collection = database
            .GetCollection<Order>(Constants.InvoicesCollection);

// find all orders having a lotnumber
var lotNumberFilter = Builders<Order>.Filter
            .Exists(o => o.LotNumber, exists:true);

var ordersWithLotNumber = await collection
            .Find(lotNumberFilter).ToListAsync();

LotNumber property has the [BsonIgnoreIfDefault] attribute assigned. This ensures that when a document having null LotNumber is inserted in the collection, this field will be totally ignored, meaning the document will not contain a lotNumber field.

On the contrary, if you omit this attribute and try to insert a document with null LotNumber, the field will be added with a null value as follow.

{
	"_id" : 0,
	"item" : "Handcrafted Steel Salad",
	"quantity" : 9,
	"lotNumber" : null, // nullable not ignored
	"shipmentDetails" : {
		"shipAddress" : "323 Edna Mission",
		"city" : "Jaquelineberg",
		"country" : "Moldova",
		"contactName" : "Eve Legros",
		"contactPhone" : "420.498.4974 x12459"
	}
}

Type operator - $type

The Type operator matches documents where the field's value is an instance of a BSON type.

Builders<T>.Filter
    .Type(doc => doc.<field>, BsonType type)

Use this operator when you need to ensure that a document's field has (or hasn't) been assigned with a specific value type.

The sample uses the Type operator to find all orders that have been shipped by checking that the ShippedDateproperty has been assigned with a DateTime value.

ElementOperators.cs
var collection = database
    .GetCollection<User>(Constants.InvoicesCollection);

// find documents with shippedDate assigned a DateTime value
var typeFilter = Builders<Order>.Filter
    .Type(o => o.ShipmentDetails.ShippedDate, BsonType.DateTime);

var shippedOrders = await collection
    .Find(typeFilter).ToListAsync();

Query for NULL values

Assuming you have a property that might get assigned with NULLvalue, you can find these documents by applying a filter on BsonType.Null types on that property.

The sample finds all documents with NULL shipment's contact phone number.

ElementOperators.cs
var collection = database
     .GetCollection<Order>(Constants.InvoicesCollection);

// search for null contact phone numbers
// the field does exists, but has null value
var nullContactPhoneFilter = Builders<Order>.Filter
     .Type(o => o.ShipmentDetails.ContactPhone, BsonType.Null);
            
var nullContactPhoneOrders = await collection
     .Find(nullContactPhoneFilter).ToListAsync();

Last updated