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;}
}
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" } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With