8

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

I have a User entity defined as

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

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

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

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

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.

1
  • 1
    Query.And? Is that what you're looking for? Commented May 29, 2013 at 19:53

1 Answer 1

14

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

See CSharp Driver Tutorial

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

This is also interesting too: How to rewrite a MongoDB C# LINQ with a Projection Requirement using a MongoCursor

Sign up to request clarification or add additional context in comments.

2 Comments

Nice I think the more LINQ approach is really what I was after from the beginning. I feel kind of dumb for not remembering how to do this, but perhaps this will save someone else a few minutes of poking around.
Don't feel dumb! :) As the popularity of MongoDB continues to grow, I'm sure it will help, so +1 for the question ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.