Reputation: 1227
I use mongodb with c# driver.I have a collection which contains subdocument
public class EntityA
{
public string Name { get; set; }
public string Description { get; set; }
public List<EntityB> BItems { get; set; }
}
public class EntityB
{
public string BName { get; set; }
public string BDesc { get; set; }
}
I want to create query and take list of EntityB
items
from a in mycollection
where BItems.Any(k => k.BName == entity.Name)
select a.BItems;
I can query nested document but when I retrive the list all other child items come to list how can I take list of BItems to meet up my criteria.I can query subdocument but when I want to take list All Bitems are coming to mylist
Upvotes: 3
Views: 4654
Reputation: 1227
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;
Upvotes: 1
Reputation: 39326
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();
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));
Upvotes: 0
Reputation: 1325
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;
Upvotes: 2