Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query collection using generic query builder

Tags:

c#

mongodb

I am using the mongocsharpdriver nuget package (version 1.11.0) to run queries against a mongo database.

When creating a query object in c# I can do this:

var query = Query.EQ("RootValue", "foo");

I can use the nicer generic query Builders instead to do this:

var query = Query<RootObject>.EQ(x=>x.RootValue, "foo");

Now consider this query::

var query = Query.EQ("Things.Value", "bar");

Here Things is a collection of objects that have a string (Value) on them. In this case the query will return any object which has a match in any of the Values of Things.

How do I write this query using the generic Query builder?

I can't work out what expression I need that will get correctly translated to what I want...

In case it makes it clearer here are the classes for my example:

public class RootObject
{
    [BsonId]
    public ObjectId Id {get; set;}
    public IEnumerable<RepeatedObject> Things {get; set;}
    public string RootValue {get; set;}
}

public class RepeatedObject
{
    public string Value {get; set;}
}
like image 254
Chris Avatar asked Dec 30 '25 23:12

Chris


1 Answers

Using this version of the driver, the following query

var query = Query<RootObject>.ElemMatch(x => x.Things, x => x.EQ(y => y.Value, "bar"));

will be translated into the desired MongoDB query:

{ Things: { $elemMatch: { Value: "bar" } } }
like image 81
dnickless Avatar answered Jan 01 '26 12:01

dnickless