I have the following C# function that uses .NET MongoDb driver and that currently works well. It excludes certain fields in RedactedPropertyList collection from being returned by all of the queries where the projection is used. However, I now need to include the /lengths/ of the excluded fields as new fields and I am struggling to make it work
private ProjectionDefinition<BsonDocument> GetFullRedactionProjection()
{
var exclusions =
RedactedPropertyList.Aggregate<string?, ProjectionDefinition<BsonDocument>?>(null,
(current, item) =>
current == null ? Builders<BsonDocument>.Projection.Exclude(item) : current.Exclude(item));
return exclusions!;
}
Any suggestions?
Instead of using a projection, you could apply a $set
stage and change the value of the redacted properties to their size in place of the actual content. In plain JSON, this stage would look like this (for redacted properties A and B):
{
"$set": {
"A": {
"$size": "$A"
},
"B": {
"$size": "$B"
}
}
}
As you are working with BsonDocument
objects, an easy way to achieve this is to build the stage as BsonDocument
and append it to the pipeline as shown in the following sample:
var collDoc = db.GetCollection<BsonDocument>("docs");
List<string> RedactedPropertyList = ["A", "B"];
List<BsonElement> assignments = RedactedPropertyList
.Select(prop => new BsonElement(prop, new BsonDocument() { { "$size", "$" + prop } }))
.ToList();
var setStage = new BsonDocument()
{
{"$set", new BsonDocument(assignments) }
};
PipelineDefinition<BsonDocument, BsonDocument> pipeline =
new EmptyPipelineDefinition<BsonDocument>();
// Add other stages as required
pipeline = pipeline.AppendStage<BsonDocument, BsonDocument, BsonDocument>(setStage);
var result = await collDoc.AggregateAsync(pipeline);
The sample above basically overwrites the existing properties with their respective length. This eliminates the need for the exclusion of the properties with a $project
stage.
If you want to change the name of the properties, you'd have to add a $set
stage first with the changed property names and then add another projection stage that excludes the original documents.