【问题标题】:Use fields that start with $ in MongoDB aggregation lookup在 MongoDB 聚合查找中使用以 $ 开头的字段
【发布时间】: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


【解决方案1】:

您可以通过在子查询中使用uncorrelated $lookup$objectToArray 来访问campaign.$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"
  } }
])

【讨论】:

  • 是的,这不是最漂亮的解决方案,但它是管道作者推荐的 jira.mongodb.org/browse/…,直到他们想出更好的东西
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-05-05
  • 2021-12-20
  • 1970-01-01
  • 2017-05-08
  • 2021-02-16
  • 2017-09-22
  • 1970-01-01
相关资源
最近更新 更多