MongoDB - Basic Filter Definition Builders & Projection

Working with MongoDB and API is really exciting and keeps astonishing me in everyday of my learning. Hence I have decided to make you guys get excited tooπŸ˜„

I have been working as a MongoDB and API developer for the past one year of my career. I use MongoDB version of 4.4 and .NET core 2.2

So now let's switch gears to the concept! Wondering how to start with the builder class - filter and project statements for your API? 

Here I show you the basic implementation of Builders.Filter and Builders.Project

Builders<TDocument>.Filter:

var filter = Builders<modelClass>.Filter.Eq(x=>x.active, true) & Builders<modelClass>.Filter.Eq(x=>x.category,"Tech");

filter |= (Builders<modelClass>.Filter.Eq(x=>x.active, false) & Builders<modelClass>.Filter.Eq(x=>x.category,"Tech"));

filter &= (Builders<modelClass>.Filter.Gte(x=>x.cost,25.5));

The above filter defined variable does the below operation:

db.modelCollection.find(
{
$and:[
{
$or:[
{"active":true,"category","Tech"},
{"active":false,"category","Tech"}
]
},
{
"cost":{$gte:25.5}
}
]
}
)

Builders<TDocument>.Project:

var project = Builders<modelClass>.Projection.Include("name").Include("active").Include("category").Exclude("_id");

Note: _id is the primary key in every mongodb document. Also _id will be considered as INCLUDE in PROJECT by default. Hence if you don't want to display(project) _id, you have to explicitly mention an EXCLUDE statement for _id.

The above project defined variable does the below mongo operation:

db.modelCollection.find({},{"name":1,"active":1,"category":1,"_id":0})

Post your queries or comments below πŸ‘‡, I will try my best to reach back with solutions. Thanks!

Comments