I need to keep a history of users' API calls. for this, I'm using MongoDB and C# driver.
Here is my mongo model class:
public class UsageModel
{
[BsonIgnore]
public static readonly string CollectionName = "ApiUsage";
[BsonRequired]
public string User { get; set; }
[BsonRequired, BsonDictionaryOptions(DictionaryRepresentation.ArrayOfArrays)]
public Dictionary<DateTime, int> History { get; private set; }
public static IMongoCollection<UsageModel> Collection
{
get => MongoDb.Database.GetCollection<UsageModel>(CollectionName);
}
public static void IncrementTodayStats(string user)
{
var filter = Builders<UsageModel>.Filter.Eq(doc => doc.User, user);
var update = Builders<UsageModel>.Update.
SetOnInsert(doc => doc.History[DateTime.Now.Date], 0).
Inc(doc => doc.History[DateTime.Now.Date], 1);
var res = Collection.UpdateOne(filter, update);
}
}
The problem is when I call IncrementTodayStats
I get this Exception:
Unable to determine the serialization information for doc => doc.History.get_Item(DateTime.Now.Date).
I don't know what I'm missing as I don't have much experience with MongoDB and Serialization, and as this answer advises I have put BsonDictionaryOptions
decorator.
I should mention that prior to incrementing History[DateTime.Now.Date]
I make sure that UsageModel
containing this dictionary has been created and I've used SetOnInsert
in case the entry for DateTime.Now.Date
has not been present in the dictionary before this request.
Any help is greatly appreciated.