检查数据库中是否存在元素

本文关键字:存在 元素 是否 数据库 检查 | 更新日期: 2023-09-27 18:36:05

我在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;
    }

有什么帮助吗?

检查数据库中是否存在元素

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

试试这个:

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

您可能需要一个"using System.Linq;"参考来编译。如果找到任何匹配项,则应返回 true。