Mongo:如何在mongo中查询特定的派生类?(使用monogcsharpdriver 1.9.2)

时间:2014-10-06 11:45:38

标签: mongodb search abstract derived

public class Person
{
    List<Contact> Contacts {get;set;}
}

public abstract class Contact
{
    string Value {get;set;}
}

public class Email : Contact
{
}

public class Chat: Contact
{
}

我为Person键入了集合。

如何在mongodb中查询特定的派生类型(比如说电子邮件),它在Value字段中有一些特定的值?

我可以将查询构建为Person.Contacts.Value =“someValue”,但如果“someValue”与任何Chat.Value匹配,则此查询返回结果。 我需要的是Query必须只搜索Email.Value字段并相应地返回结果?

提前感谢你。

1 个答案:

答案 0 :(得分:3)

以下应该这样做。诀窍是添加&#34; _t&#34;到查询。这可以手动完成,或者如下所示,使用OfType。

var emails = db.GetCollection<Contact>("contacts")
    .AsQueryable()
    .OfType<Email>()
    .Where(x => x.Value == "someValue");