public void SetDocumentId(object document, object id)
{
if (document == null)
{
throw new ArgumentNullException("document");
}
if (id == null)
{
throw new ArgumentNullException("id");
}
var bsonDocument = (BsonDocument)document;
var idBsonValue = id as BsonValue;
if (idBsonValue == null)
{
idBsonValue = BsonValue.Create(id); // be helpful and provide automatic conversion to BsonValue if necessary
}
BsonElement idElement;
if (bsonDocument.TryGetElement("_id", out idElement))
{
idElement.Value = idBsonValue;
}
else
{
bsonDocument.InsertAt(0, new BsonElement("_id", idBsonValue));
}
}
}