我在 mongodb 上有一个这样的查询:
db = db.getSiblingDB("his");
db.getCollection("Account").aggregate(
[
{
"$lookup" : {
"from" : "LinkedEntities",
"let" : {
"account_id" : "$AccountId",
"institutionGroup_id" : "$InstitutionGroupId"
},
"pipeline" : [
{
"$match" : {
"$expr" : {
"$and" : [
{
"$eq" : [
"$InstitutionGroupId",
"$$institutionGroup_id"
]
},
{
"$eq" : [
"$AccountId",
"$$account_id"
]
}
]
}
}
},
{
"$project" : {
"AccountId" : NumberInt(0),
"_id" : NumberInt(0)
}
}
],
"as" : "AccountwithLinkedEntities"
}
}
]
我需要使用 FluentHelper 将其迁移到 mongdb 驱动程序 我尝试这样做,但与我的 mongodb 查询不匹配:
var filter = Builders<Account>.Filter.Eq(a => a.InstitutionGroupId, institutionGroupId)
& Builders<Account>.Filter.Eq(a => a.AccountId, accountId);
var accountwithLinkedEntities = await _mongoDbContext.Accounts.Aggregate().Match(filter)
.Lookup<Account, LinkedEntities, AccountwithLinkedEntities>(_mongoDbContext.LinkedEntities,
x => x.AccountId,
y => y.AccountId,
x => x.InnerLinkedEntities)
.ToListAsync();
return accountwithLinkedEntities;
如何使用流畅的语法将第一个查询转换为 C#。
致以诚挚的问候
因为它很大,所以将其写为答案:
你的例子是错误的。您将
$match
聚合阶段放在查找之外,并且通常使用不同形式的查找。请参阅以下几点:
您始终可以向类型化助手提供原始 MQL 查询(基于字符串),因为所有驱动程序的助手(包括 $lookup)都允许从字符串隐式创建。可以在此处找到一个示例。另一个例子可以在这里找到(参见
Unsupported LINQ or Builder expressions
)。
但是,您的案例似乎支持更像 c# 的方法。您应该使用允许传递聚合管道的this重载。要创建聚合管道,您可以使用以下代码片段:
var pipeline = new Driver.EmptyPipelineDefinition<..YOUR_TYPE..>()
.Match(..match condition in typed or string based (raw) forms..)
.Project(..projection condition in typed or string based (raw) forms..);
注意
let
参数只能以 BsonDocument 形式提供,这意味着您不能使用任何类型的表单。所以会是:
...
foreignCollection: ...,
let: BsonDocument.Parse(@$"
{{
""account_id"" : {accountIdVariable},
""institutionGroup_id"" : {institutionGroupId}
}}");
lookupPipeline: pipeline,
...