Bri*_*ver 8 c# mongodb mongodb-query mongodb-.net-driver
假设我在MongoDB中有以下文档结构.
{
_id: ####,
Ancestors: [
{ _id: 1, Name: "asdf" },
{ _id: 2, Name: "jkl;" },
...
]
}
Run Code Online (Sandbox Code Playgroud)
我想找到包含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; }
}
Run Code Online (Sandbox Code Playgroud)
我的问题是:如何使用C#驱动程序编写强类型查询,以便我不必将"Ancestors._id"作为字符串传入?我希望能够做类似的事情,Query<Project>.EQ(p => p.Id, rootProjectId)以便我可以使用成员表达式,让类映射告诉驱动程序它应该使用"Ancestors._id".
Roi*_*Tal 13
在这种情况下,ElemMatch是你的朋友.
尝试以下方法:
var ancestorsQuery = Query<ProjectRef>.EQ(pr => pr.Id, rootProjectId);
var finalQuery = Query<Project>.ElemMatch(p => p.Ancestors, builder => ancestorsQuery));
Run Code Online (Sandbox Code Playgroud)
在Projects集合的Find命令中使用finalQuery.
| 归档时间: |
|
| 查看次数: |
12059 次 |
| 最近记录: |