FilterDefinition <MyObject>-如何查询数组中的对象?

时间:2019-06-11 03:09:31

标签: c# mongodb

我在下面有一个列表,我不知道如何查询数组中的对象

class a
{
   public string Name{get;set;}
   public List<b> Attr{get;set;}
}

class b
{
   public string Card{get;set;}
   public sring SN{get;set;}
}

C#如何编写查询?使用FilterDefinition

FilterDefinition<a> filter = Builders<a>.Filter.Empty;
a.Eq( q=>q.Attr.Card, '001') ..., wrong...

1 个答案:

答案 0 :(得分:0)

您需要ElemMatch。然后,您可以将数组项的过滤器作为FilterDefinition<b>或lambda表达式传递:

FilterDefinition<a> filter = Builders<a>.Filter.ElemMatch(q => q.Attr, Builders<b>.Filter.Eq(attr => attr.Card, "001"));

FilterDefinition<a> filter = Builders<a>.Filter.ElemMatch(q => q.Attr, attr => attr.Card == "001");