Skip to content

Instantly share code, notes, and snippets.

@chrisnicola
Created December 22, 2011 20:33
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save chrisnicola/1511744 to your computer and use it in GitHub Desktop.
Save chrisnicola/1511744 to your computer and use it in GitHub Desktop.
Mongo C# extension to compare BsonDocument and BsonValue objects
public static bool SameAs(this BsonDocument source, BsonDocument other, params string[] ignoreFields)
{
var elements = source.Elements.Where(x => !ignoreFields.Contains(x.Name)).ToArray();
if (elements.Length == 0 && other.Elements.Where(x => !ignoreFields.Contains(x.Name)).Any()) return false;
foreach (var element in source.Elements)
{
if (ignoreFields.Contains(element.Name)) continue;
if (!other.Names.Contains(element.Name)) return false;
var value = element.Value;
var otherValue = other[element.Name];
if (!value.SameAs(otherValue)) return false;
}
return true;
}
public static bool SameAs(this BsonValue value, BsonValue otherValue)
{
if (value.IsBsonDocument)
{
if (!otherValue.IsBsonDocument) return false;
if (!value.AsBsonDocument.SameAs(otherValue.AsBsonDocument)) return false;
}
else if (value.IsBsonArray)
{
if (!otherValue.IsBsonArray) return false;
if (value.AsBsonArray.Count != otherValue.AsBsonArray.Count) return false;
var array = value.AsBsonArray.OrderBy(x => x).ToArray();
var otherArray = otherValue.AsBsonArray.OrderBy(x => x).ToArray();
return !array.Where((t, i) => !t.SameAs(otherArray[i])).Any();
}
else return value.Equals(otherValue);
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment