如何使用C#在mongodb中增加字段 [英] How do you increment a field in mongodb using c#

查看:577
本文介绍了如何使用C#在mongodb中增加字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这会很简单,但是我的值保持不变(0).

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

我想做的是,当用户收到未读的消息时,将其UnreadMessages字段增加,然后在收到未读的消息时,将其减少.所以我认为这样的代码会起作用:

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 :)

更新

这是我的助手班:

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

并且由于Travis的回答,我得以实现:

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

推荐答案

不确定您的助手会做什么.这是我使用的有效代码段:

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

因此,查询"查找文档,更新执行增量,而FindAndModify将它们放在一起并实际上命中数据库.

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

这篇关于如何使用C#在mongodb中增加字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆