Mongodb C# query nested document Mongodb C# query nested document mongodb mongodb

Mongodb C# query nested document


If i understood you correctly you want to return BItems collections when BName is equals to it's parents Name field? If that is the case than it goes like this:

var result = from a in mycollection             from b in a.BItems             where a.Name == b.BName             select b;


AS I Understand SelectMany meets to unwind propert in mongodb and to use unwind property we cannot add criteria directly.

MongoDB finding nested objects that meet criteria

       var result = from k in (from a in col.AsQueryable()                     from b in a.Columns                             select b) where k.ColumnName==a.Name select k;


Well, now I tested with MongoDB C# driver 2.2.3 and MongoDB 3.2.1 and indeed SelectMany is already supported, so you can also do this:

 var entities= mycollection.AsQueryable<EntityA>()                           .SelectMany(e=>e.BItems, (e,b)=>new {entityA=e,bitem=b})                           .Where(t => t.entityA.Name == t.bitem.Name)                           .Select(t=>t.bitem)                           .ToList();

Update

Another possible solution could be fetching first the data and filtering latter in memory:

var entities= mycollection.AsQueryable<EntityA>()                          .Select(e=>new{e.Name,e.BItems}).ToList();var result=entities.SelectMany(e=>e.BItems.Where(b=>b.Name==e.Name));