【问题标题】:Check if element exists in the database检查数据库中是否存在元素
【发布时间】:2015-01-04 23:54:21
【问题描述】:

我在 MongoDB 中有一个按如下方式组织的集合:

{
    "_id"      : ObjectId("xxxxxx"),
    "Username" : username
    "Password" : encrypted_password
    "Position" : position
    .....
}
{
    "_id"      : ObjectId("yyyyyy"),
    "Username" : username2
    "Password" : encrypted_password2
    "Position" : position2
    .....
}

我想遍历集合并检查是否存在用户名+密码组合,但我似乎无法弄清楚:/

我正在使用带有 C# 的 MongoDB 驱动程序,这就是我目前所拥有的:

    public bool DoesSaveDataExist(String database, String collection, string username, string password)
    {
        MongoClient client = new MongoClient(); // connect to localhost
        MongoServer server = client.GetServer();
        MongoDatabase test = server.GetDatabase(database);

        var GetFromCollection = test.GetCollection<BsonDocument>(collection);

        byte[] passwordToByte = System.Text.Encoding.ASCII.GetBytes(password);
        passwordToByte = new System.Security.Cryptography.SHA256Managed().ComputeHash(passwordToByte);
        String hash = System.Text.Encoding.ASCII.GetString(passwordToByte);

        IMongoQuery query = new QueryDocument {
            { "Player Name", username },
            { "Password", hash}
        };

        return false;
    }

有什么帮助吗?

【问题讨论】:

  • SHA 太快,无法存储密码。您需要使用加盐的迭代哈希。使用 PBKDFv2。此外,哈希不是 ASCII;使用 base63 或存储一个字节数组。

标签: c# mongodb bson database


【解决方案1】:

您在数据库中使用“用户名”,在查询中使用“玩家名”...这就是为什么您不匹配 MongoDB 中的任何文档。

【讨论】:

    【解决方案2】:

    试试这个:

    return GetFromCollection.Find(Query.And(Query.EQ("Username", username), Query.EQ("Password", hash))).Any();
    

    您可能需要一个“使用 System.Linq;”对此进行编译的参考。 如果找到任何匹配项,这应该返回 true。

    【讨论】:

    • 谢谢!在那场比赛之后,我将如何编辑特定的后续条目?例如,在该用户名之后找到的“职位”? :S 我可以调用 Update.Set("Position", "New Position");但不确定如何对特定用户...
    • 如果你最后没有调用 Any 方法,调用将返回具有给定名称和密码的用户集合(可能最多单个用户),所以你可以这样做那个,然后返回那个。
    • 我正在尝试,但它没有进入我的 foreach 循环这样做:S 除非我理解光标错误? var GetFromCollection = test.GetCollection(collection); var query = GetFromCollection.Find(Query.And(Query.EQ("Username", username),Query.EQ("Password", hash))); foreach (var q in query) { MessageBox.Show(q.ToString()); }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-20
    • 1970-01-01
    相关资源
    最近更新 更多