简体   繁体   中英

Increment a value inside dictionary on MongoDb C#

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 being competed between several requests, I can't just bring the object to the server, increment the value and then save 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

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

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM