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:
2nd Approach:
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" } } } } };
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
Post a Comment