0

我有一个使用 Spring Data 的 Spring 应用程序填充的 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 字段名称可能不以“$”开头。

逃离美元没有任何影响,我也找不到任何以美元开头的领域的例子。

4

1 回答 1

2

您可以通过在子查询中使用不相关的 $lookup$objectToArraycampaign.$id来解决它来访问:

db.emailCampaign.aggregate([
  { $lookup: {
    from: "campaignDelivery",
    let: { id: "$_id" },
    pipeline: [
      { $addFields: {
        refId: { $arrayElemAt: [
          { $filter: {
            input: { $objectToArray: "$campaign" },
            cond: { $eq: [ "$$this.k", { $literal: "$id" } ] }
          } }
          , 0
        ] }
      } },
      { $match: {
        $expr: { $eq: [
          "$refId.v",
          "$$id"
        ] }
      } },
      { $project: {
        refId: 0
      } }
    ],
    as: "deliveries"
  } }
])
于 2019-10-31T18:49:07.600 回答