本文介绍了使用C#驱动程序进行MongoDB的多字段查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法弄清楚要完成的语法.如前所述,我正在为MongoDB使用C#驱动程序.

I'm having trouble figuring out syntax for what I'm trying to accomplish. As stated I'm using the C# driver for MongoDB.

我的用户实体定义为

[BsonIgnoreExtraElements]
public class User : MongoEntity
{
    [BsonElement]
    public string Username { get; set; }

    [BsonElement]
    public string Password { get; set; }

    [BsonElement]
    public string Email { get; set; }
}

我还有一个UserService类,该类对mongo数据库中的User集合执行操作.下面是我如何创建一个真正的简单登录示例的示例.

I also have a UserService class that performs actions against the User collection in my mongo database. Below is an example of how i'm creating a real simple login example.

public UserPresentation Login(string username, string password)
{
    var entityQuery = Query<User>.EQ(e => e.Username, username.ToUpper());

    var entity = this.MongoConnectionHandler.MongoCollection.FindOne(entityQuery);

    return (entity != null && entity.Id.ToString().Length > 0 && entity.Password == password) ? new UserPresentation(entity) : null;
}

这可行,但是我的问题是...而不是创建一个仅查找Username == username的查询,返回该元素,然后在if语句中比较密码,我可以以某种方式将更多字段附加到初始entityQuery对象.

This works, however my question is... instead of creating a Query that only looks for Username == username, returning the element and then comparing the password in an if statement, can I somehow append more fields to the intial entityQuery object.

推荐答案

您可以像这样使用Query.And() ...

You can use Query.And() like this...

var entityQuery = Query.And(
                      Query<User>.EQ(e => e.Username, username.ToUpper()),
                      Query<User>.EQ(e => e.Password, password)
                  );

请参见 CSharp驱动程序指南

或者您可以使用LINQ样式,请参见: CSharp驱动程序LINQ教程

Or you could do it LINQ style, see: CSharp Driver LINQ Tutorial

这也很有趣:如何使用投影重写MongoDB C#LINQ使用MongoCursor的要求

这篇关于使用C#驱动程序进行MongoDB的多字段查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 20:04