Multi-Field Queries Using C # Driver for MongoDB

I find it difficult to understand the syntax of what I'm trying to accomplish. As said, I am using the C # driver for MongoDB.

I have a custom object 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 takes action against the User collection in my mongo database. Below is an example of how I am 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 that instead of creating a query that searches only for the username Username, it returns an element and then compares the password in the if statement, can I somehow add more fields to the intial entityQuery .

+6
source share
1 answer

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 Tutorial

Or you can do it in LINQ style, see CSHarp Driver LINQ Tutorial

This is also interesting: How to rewrite LINQ MongoDB C # with forecasting requirements using MongoCursor

+12
source

Source: https://habr.com/ru/post/946113/


All Articles