pedrommuller
pedrommuller

Reputation: 16056

Calculate a counter in MongoDB

I need to create a counter to track "likes" / "hearts" over a multimedia item displayed in my webpage most likely an image or a video, this functionality is pretty much standard and a very similar case to what facebook / Instagram / Dribble does.

I'd like some advice of how can I implement such kind of counter and I proceed with this implementation bearing in mind the best performance of it.

My entity model so far is the following:

public class Portfolio:Entity
{
    public int UserId { get; set; }
    public string Url { get; set; }
    public string Thumbnail { get; set; }
    public string FullSizeImage { get; set; }
    public string Description { get; set; }
    public MediaType MediaType { get; set; }
}

please take a look to a dribbble screenshot for reference enter image description here

I'm using C# and MongoDB Driver / MongoRepository

Upvotes: 2

Views: 4226

Answers (1)

Craig Wilson
Craig Wilson

Reputation: 12624

MongoDB supports atomic increment operations. You can see the docs for this here: http://docs.mongodb.org/manual/reference/operator/inc/

db.portfolio.update({ _id: 10},{ $inc: { likes: 1 } });

This will update the likes field by 1 of the portfolio with an _id of 10. Even if 2, or 10, different users do this at the same time, the increment operation will count them all.

In C#, there are a number of ways to do this, the easiest being to use the builders.

var query = Query<Portfolio>.EQ(x => x.UserId, 10);
var update = Update<Portfolio>.Inc(x => x.Likes, 1);

collection.Update(query, update);

Upvotes: 4

Related Questions