Strongly typed query on a nested field using MongoDB C # driver 2.2

Consider the following structures

public class Parent { public ObjectId Id { get; set; } public IEnumerable<Child> Children { get; set; } } public class Child { public string Value { get; set; } } 

I want to find all the parent objects whose child values ​​are a superset of the ie array

 var parents = new List<Parent>(); var values = new[] { "A", "B", "C" }; parents.Where(x => !values.Except(x.Children.Select(y => y.Value)).Any()); 

or

 { "Children.Value": { $all: ["A", "B", "C"] } } 

I would like to do this in a printed way, but the predicate translator does not support Enumerable. Choose to not help:

 Builders<Parent>.Filter.All(x => x.Children.Select(y => y.Value), values); 

I am currently using this workaround:

 var filters = values.Select(x => Builders<Parent>.Filter.Where(y => y.Children.Any(z => z.Value == x))); Builders<Parent>.Filter.And(filters); 

Is there a better way without using a magic field name string?

+6
source share
1 answer
 IMongoClient _client = new MongoClient(@"mongodb://..."); IMongoDatabase _database = _client.GetDatabase("..."); IMongoCollection<Parent> _collection = _database.GetCollection<Parent>("q35135879"); var ca = new Child { Value = "A" }; var cb = new Child { Value = "B" }; var cc = new Child { Value = "C" }; var fdb = Builders<Parent>.Filter; var filterLinq = fdb.All (x=>x.Children, new[] {ca, cb, cc}); var filterFieldDefinition = fdb.All("Children", new[] { ca, cb, cc }); var found1 = _collection.Find(filterLinq).ToList(); var found2 = _collection.Find(filterFieldDefinition ).ToList(); CollectionAssert.AreEqual(found1, found2); 
0
source

All Articles