Created
November 13, 2022 21:26
-
-
Save joeyguerra/cf72c783d378e610802830ac790d762b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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