Skip to content

Instantly share code, notes, and snippets.

@joeyguerra
Created November 13, 2022 21:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joeyguerra/cf72c783d378e610802830ac790d762b to your computer and use it in GitHub Desktop.
Save joeyguerra/cf72c783d378e610802830ac790d762b to your computer and use it in GitHub Desktop.
using MongoDB.Bson;
public static class BsonDocumentExtentions
{
public static void RemoveNullElements(this BsonDocument documents)
{
RemoveNulls(documents);
}
public static BsonDocument RemoveNulls(BsonDocument document)
{
var counter = document.ElementCount - 1;
var elem = document.ElementAt(counter);
while(counter >= 0){
RemoveIfNull(elem, document);
counter--;
if(counter < 0) break;
elem = document.ElementAt(counter);
}
return document;
}
public static void RemoveIfNull(BsonElement element, BsonDocument document)
{
if(element.Value == BsonNull.Value || element.Value == null){
document.RemoveElement(element);
} else {
try{
RemoveNulls(element.Value.ToBsonDocument());
if(element.Value.ToBsonDocument().ElementCount == 0){
document.RemoveElement(element);
}
}catch(InvalidOperationException e){
Console.WriteLine($"Exception happened trying to remove nulls = {e}");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment