10

假设我在 MongoDB 中有以下文档结构。

{
    _id: ####,
    Ancestors: [
        { _id: 1, Name: "asdf" },
        { _id: 2, Name: "jkl;" },
        ...
    ]
}

我想找到每个包含 Ancestor 的文档,其中 Ancestor 的 _id 为 2。

我可以使用以下命令在 mongo shell 中运行此查询: db.projects.find({"Ancestors._id": 2})

我还可以使用官方 C# 驱动程序运行此查询: Query.EQ("Ancestors._id", new BsonInt32(rootProjectId)).

这是我的 POCO;我使用的实际类具有比这更多的属性,但我不想用不必要的细节来混淆这个问题:

public class Project
{
    public int Id { get; set; }
    public List<ProjectRef> Ancestors { get; set; }
}

public class ProjectRef
{
    public int Id { get; set; }
    public string Name { get; set; }
}

我的问题是:如何使用 C# 驱动程序编写强类型查询,这样我就不必将“Ancestors._id”作为字符串传递?我希望能够做类似的事情,Query<Project>.EQ(p => p.Id, rootProjectId)以便我可以使用成员表达式并让类映射告诉驱动程序它应该使用“Ancestors._id”。

4

1 回答 1

14

在这种情况下, ElemMatch是您的朋友。

尝试以下操作:

var ancestorsQuery = Query<ProjectRef>.EQ(pr => pr.Id, rootProjectId);
var finalQuery = Query<Project>.ElemMatch(p => p.Ancestors, builder => ancestorsQuery));

在 Projects 集合的 Find 命令中使用 finalQuery。

于 2013-09-17T21:24:36.753 回答