How do you increment a field in mongodb using c#

爷,独闯天下 提交于 2019-11-30 04:49:47

问题


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>();

回答1:


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.



来源:https://stackoverflow.com/questions/10566602/how-do-you-increment-a-field-in-mongodb-using-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!