Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8295915
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 8, 20262026-06-08T14:46:36+00:00 2026-06-08T14:46:36+00:00

*Mongo Newbie here I have a document containing several hundred numeric fields which I

  • 0

*Mongo Newbie here

I have a document containing several hundred numeric fields which I need to query in combination.

var collection = _myDB.GetCollection<MyDocument>("collection");
IMongoQuery mongoQuery; // = Query.GT("field", value1).LT(value2);
foreach (MyObject queryObj in Queries)
{
    // I have several hundred fields such as Height, that are in queryObj
    // how do I build a "boolean" query in C# 
    mongoQuery = Query.GTE("Height", Convert.ToInt16(queryObj.Height * lowerbound));
}

I have several hundred fields such as Height (e.g. Width, Area, Perimeter etc.), that are in queryObj how do I build a “boolean” query in C# that combines range queries for each field in conjunction.

I have tried to use the example Query.GT(“field”, value1).LT(value2);, however the compiler does not accept the LT(Value) construct. In any event I need to be able to build a complex boolean query by looping through each of the numeric field values.

Thanks for helping a newbie out.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-08T14:46:38+00:00Added an answer on June 8, 2026 at 2:46 pm

    EDIT 3:

    Ok, it looks like you already have code in place to build the complicated query. In that case, you just needed to fix the compiler issue. Am assuming you want to do the following (x > 20 && x < 40) && (y > 30 && y < 50) …

    var collection = _myDB.GetCollection<MyDocument>("collection");
    var queries = new List<IMongoQuery>();
    
    foreach (MyObject queryObj in Queries)
    {
        //I have several hundred fields such as Height, that are in queryObj
        //how do I build a "boolean" query in C# 
    
        var lowerBoundQuery = Query.GTE("Height", Convert.ToInt16(queryObj.Height * lowerbound));
        var upperBoundQuery = Query.LTE("Height", Convert.ToInt16(queryObj.Height * upperbound));
    
        var query = Query.And(lowerBoundQuery, upperBoundQuery);
        queries.Add(query);
    }
    
    var finalQuery = Query.And(queries); 
    /*
        if you want to instead do an OR,
        var finalQuery = Query.Or(queries); 
    */
    

    Original Answer.

    var list = _myDb.GetCollection<MyDoc>("CollectionName")
                    .AsQueryable<MyDoc>()
                    .Where(x => 
                             x.Height > 20 && 
                             x.Height < 40)
                    .ToList();
    

    I have tried to use the example Query.GT(“field”, value1).LT(value2);,
    however the compiler does not accept the LT(Value) construct.

    You can query MongoDB using linq, if you are using the official C# driver. That ought to solve the compiler issue I think.

    The more interesting question I have in mind is, how are you going to construct that complicated boolean query?

    One option is to dynamically build an Expression and then pass that to the Where

    My colleague is using the following code for something similar…

        public static IQueryable<T> Where<T>(this IQueryable<T> query,
            string column, object value, WhereOperation operation)
        {
            if (string.IsNullOrEmpty(column))
                return query;
    
            ParameterExpression parameter = Expression.Parameter(query.ElementType, "p");
    
            MemberExpression memberAccess = null;
            foreach (var property in column.Split('.'))
                memberAccess = MemberExpression.Property
                   (memberAccess ?? (parameter as Expression), property);
    
            //change param value type
            //necessary to getting bool from string
            ConstantExpression filter = Expression.Constant
                (
                    Convert.ChangeType(value, memberAccess.Type)
                );
    
            //switch operation
            Expression condition = null;
            LambdaExpression lambda = null;
            switch (operation)
            {
                //equal ==
                case WhereOperation.Equal:
                    condition = Expression.Equal(memberAccess, filter);
                    lambda = Expression.Lambda(condition, parameter);
                    break;
                //not equal !=
                case WhereOperation.NotEqual:
                    condition = Expression.NotEqual(memberAccess, filter);
                    lambda = Expression.Lambda(condition, parameter);
                    break;
                //string.Contains()
                case WhereOperation.Contains:
                    condition = Expression.Call(memberAccess,
                        typeof(string).GetMethod("Contains"),
                        Expression.Constant(value));
                    lambda = Expression.Lambda(condition, parameter);
                    break;
            }
    
    
            MethodCallExpression result = Expression.Call(
                   typeof(Queryable), "Where",
                   new[] { query.ElementType },
                   query.Expression,
                   lambda);
    
            return query.Provider.CreateQuery<T>(result);
        }
    
    public enum WhereOperation
    {
        Equal,
        NotEqual,
        Contains
    }
    

    Currently it only supports == && !=, but it shouldn’t be that difficult to implement >= or <= …

    You could get some hints from the Expression class: http://msdn.microsoft.com/en-us/library/system.linq.expressions.expression.aspx

    EDIT:

    var props = ["Height", "Weight", "Age"];
    var query = _myDb.GetCollection<MyDoc>("CName").AsQueryable<MyDoc>();
    foreach (var prop in props) 
    {
       query = query.Where(prop, GetLowerLimit(queryObj, prop), WhereOperation.Between, GetUpperLimit(queryObj, prop));  
    }
    // the above query when iterated over, will result in a where clause that joins each individual `prop\condition` with an `AND`. 
    // The code above will not compile. The `Where` function I wrote doesnt accept 4 parameters. You will need to implement the logic for that yourself. Though it ought to be straight forward I think... 
    

    EDIT 2:

    If you don’t want to use linq, you can still use Mongo Query. You will just need to craft your queries using the Query.And() and Query.Or().

            // I think this might be deprecated. Please refer the release notes for the C# driver version 1.5.0  
            Query.And(Query.GTE("Salary", new BsonDouble(20)), Query.LTE("Salary", new BsonDouble(40)), Query.GTE("Height", new BsonDouble(20)), Query.LTE("Height", new BsonDouble(40)))
    
            // strongly typed version
            new QueryBuilder<Employee>().And(Query<Employee>.GTE(x => x.Salary, 40), Query<Employee>.LTE(x => x.Salary, 60), Query<Employee>.GTE(x => x.HourlyRateToClients, 40), Query<Employee>.LTE(x => x.HourlyRateToClients, 60))
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a mongo collection which has documents with two fields fieldA and fieldB,
Completely new to mongo here. I have following fields in on of my mysql
I have a mongo query to be executed : query = { dateField :
I use mongo, and I have a little problem here. I want to get
I have a Mongo DB column which contains values of the sort 1001,100 and
I have the following mongo document: { _id: 'someid', name: 'John Doe', address: {
I have a Mongo collection called documents which has the following structure: { name:
*Mongo newbie here (using Mongo C# Driver on Windows) Hi, I am evaluating Mongo
I'm a perl newbie. I have a code in which a variable is loaded
In Mongo my understanding is that you can have databases and collections. I'm working

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.