【发布时间】:2020-02-27 03:14:22
【问题描述】:
我有一个由 Spring 应用程序使用 Spring Data 填充的 MongoDB 数据库。我想执行手动查询以加入两个集合并从这些数据中提取一些统计信息。
第一个集合名为emailCampaign,包含以下信息(简化):
{
"_id" : ObjectId("5db85687307b0a0d184448db"),
"name" : "Welcome email",
"subject" : "¡Welcome {{ user.name }}!",
"status" : "Sent",
"_class" : "com.mycompany.EmailCampaign"
}
第二个集合名为campaignDelivery,包含以下信息(简化):
/* 1 */
{
"_id" : ObjectId("5db183fb307b0aef3113361f"),
"campaign" : {
"$ref" : "emailCampaign",
"$id" : ObjectId("5db85687307b0a0d184448db")
},
"deliveries" : 3,
"_class" : "com.mycompany.CampaignDelivery"
}
/* 2 */
{
"_id" : ObjectId("5db85f2c307b0a0d184448e1"),
"campaign" : {
"$ref" : "emailCampaign",
"$id" : ObjectId("5db85687307b0a0d184448db")
},
"deliveries" : 5,
"_class" : "com.mycompany.CampaignDelivery"
}
最终我想获得两个 deliveries 字段的总和,但现在我坚持使用基本的 JOIN:
db.emailCampaign.aggregate([
{
$lookup: {
from: 'campaignDelivery',
localField: '_id',
foreignField: 'campaign.$id',
as: 'deliveries'
}
}
])
抛出以下错误:
FieldPath 字段名称不能以“$”开头。
转义美元没有任何影响,我也找不到任何以美元开头的字段示例。
【问题讨论】:
标签: mongodb mongodb-query aggregation-framework mongodb-lookup