0

I need to increment a value that is stored inside a dictionary, the structure of my object is (basically) the following:

public class OrderDetails : EntityBase
{
    public int OrderId { get; set; }
    public Dictionary<int, int> TotalViewsPerUser { get; set; }
}

As this object can be competed between several requests, I can't just bring the object to the server, increment the value and then save it again.

So, what I need to do is increment the value of the variable TotalViewsPerUser, the dictionary key is the UserId. If there is no key, I need to insert the key and start with the value 1.

I looked for some examples, of the use of "Inc" and I found the following example, but, I could not make it work, because Mongo would not insert the key.

What I did is:

var update = Builders<OrderDetails>.Update
            .Inc($"totalViewsPerUser.{userId}.v", 1);

Increment Dictionary Value in MongoDB C# Driver

Yong Shun
  • 35,286
  • 4
  • 24
  • 46

1 Answers1

2

From $inc Behavior,

If the field does not exist, $inc creates the field and sets the field to the specified value.

While TotalViewsPerUser is Dictionary<int, int> type, the value would be:

"totalViewsPerUser" : {
  1: 1
}

in the document. You should not specify the .v for the update field.

var update = Builders<OrderDetails>.Update
    .Inc($"totalViewsPerUser.{userId}", 1);

UpdateResult updateResult = _collection.UpdateMany(
    FilterDefinition<OrderDetails>.Empty,
    update);

Demo

enter image description here

Yong Shun
  • 35,286
  • 4
  • 24
  • 46