Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you increment a field in mongodb using c#

Thought this would be pretty straight forward, but my value is remaining the same (0).

What I'd like to do is increment my UnreadMessages field when the user receives a message they haven't read and then decrement it when they have. So I thought code like this would work:

var userHelper = new MongoHelper<User>();
//increment
userHelper.Collection.Update(Query.EQ("Id", userId.ToId()), Update.Inc("UnreadMessages", 1));
//decrement
userHelper.Collection.Update(Query.EQ("Id", userId.ToId()), Update.Inc("UnreadMessages", -1));

After running these no errors are thrown but the value doesn't change either. And no I'm not running one after the other as the code above could be interpreted :)

Update

Here's my helper class:

public class MongoHelper<T> : Sandbox.Services.IMongoHelper<T> where T : class
{
    public MongoCollection<T> Collection { get; private set; }

    public MongoHelper()
    {
        var con = new MongoConnectionStringBuilder(ConfigurationManager.ConnectionStrings["MongoDB"].ConnectionString);
        var server = MongoServer.Create(con);
        var db = server.GetDatabase(con.DatabaseName);
        Collection = db.GetCollection<T>(typeof(T).Name.ToLower());
    }
}

and thanks to Travis' answer I was able to pull this off:

MongoHelper<UserDocument> userHelper = new MongoHelper<UserDocument>();
            var user = userHelper.Collection.FindAndModify(Query.EQ("Username", "a"), SortBy.Null, Update.Inc("MessageCount", 1), true).GetModifiedDocumentAs<UserDocument>();
like image 983
rball Avatar asked May 12 '12 19:05

rball


People also ask

How to Increment field value in MongoDB?

The $inc operator increments a field by a specified value and has the following form: { $inc: { <field1>: <amount1>, <field2>: <amount2>, ... } } To specify a <field> in an embedded document or in an array, use dot notation.

What is $Set in MongoDB?

$set outputs documents that contain all existing fields from the input documents and newly added fields. The $set stage is an alias for $addFields. Both stages are equivalent to a $project stage that explicitly specifies all existing fields in the input documents and adds the new fields.


1 Answers

Not sure what your helper does. Here is a working snippet I use:

        var query = Query.And(Query.EQ("_id", keyName));
        var sortBy = SortBy.Null;
        var update = Update.Inc("KeyValue", adjustmentAmount);
        var result = collection.FindAndModify(query, sortBy, update, true);

So, "query" finds the document, update does the increment, and FindAndModify puts them together and actually hits the database.

like image 137
Travis Laborde Avatar answered Oct 28 '22 20:10

Travis Laborde