MongoDB Aggregations: $cond in C#

When converting mongoDB $cond (https://docs.mongodb.com/manual/reference/operator/aggregation/cond/) aggregation query some times it seems really complex to write in C#.

MongoDB has provided 2 different ways to write $cond statement.

1st Approach:
{ $cond: { if: <boolean-expression>, then: <true-case>, else: <false-case-> } }
or

2nd Approach:
{ $cond: [ <boolean-expression>, <true-case>, <false-case> ] }
In order to reduce the complexity of $cond statement,
it is always good to use the 2nd Approach, because it will reduce the number of BsonDocumnets which will require when writing the aggregation in C#.

So in the following example, I have used a $redact (https://docs.mongodb.com/manual/reference/operator/aggregation/redact/) which use to drop objects with a condition statement. So if a field in that object does not matched with a given value that object will dropped.

MongoDB Aggregation:
$redact { $cond : [ { $gte : [ { $size : "$Messages"}, 2 ] }, "$$KEEP", "$$PRUNE" ] }

Aggregation to C#:
var redactTickets = new BsonDocument { { "$redact", new BsonDocument { { "$cond", new BsonArray { new BsonDocument { { "$gte", new BsonArray { new BsonDocument { { "$size", "$Messages" } }, 2 } } }, "$$KEEP", "$$PRUNE" } } } } };




Comments

Popular posts from this blog

Deploy Angular 8 app to Azure with Azure DevOps

Apache ActiveMQ 5 with .Net Core 3.1 and C#

Firebase with.Net Core and C#