【问题标题】:MongoDB using aggregation compare two array id's and update timeMongoDB使用聚合比较两个数组ID和更新时间
【发布时间】:2021-04-02 00:20:55
【问题描述】:

在 MongoDB 中,我在同一个文档中有两个数组,它们有共同的 id 字段。我想在 id 上合并这两个匹配,并在匹配时更新时间值。

mcq:[
{
id:1,
answer:A,
time:0
},
{
id:2,
answer:F,
time:0
},
{
id:3,
answer:A,
time:0
},
{
id:4,
answer:B,
time:0
}
]

activity:[
{
id:1,
time:21.2
},
{
id:3,
time:10.3
}
]

如果id 中有匹配项,我希望最终数组的时间从activity 更新

final=[
    {
    id:1,
    answer:A,
    time:21.2
    },
    {
    id:2,
    answer:F,
    time:0
    },
    {
    id:3,
    answer:A,
    time:10.3
    }
    {
    id:4
    answer:B,
    time:0
    }
    ]

我已经尝试在聚合中使用以下,但所有 id 的时间都相同

{
    '$addFields': {
      'final': {
        '$map': {
          'input': '$mcq', 
          'as': 'c', 
          'in': {
            'id': '$$c.id', 
            'time': {
              '$arrayElemAt': [
                '$activity.time', {
                  '$indexOfArray': [
                    '$activity.id', '$$c.id'
                  ]
                }
              ]
            }, 
            'answer': '$$c.answer'
          }
        }
      }
    }
  }

【问题讨论】:

  • 您认为提供的答案中是否有某些内容无法解决您的问题?如果是这样,请对答案发表评论,以澄清究竟需要解决哪些尚未解决的问题。如果它确实回答了您提出的问题,请注意Accept your Answers您提出的问题

标签: mongodb aggregation-framework


【解决方案1】:

你可以试试,

  • $map 迭代 mcq 的外观,
  • $reduce循环activity,设置mcq.time为初始值,判断id是否匹配则返回时间,否则返回初始值,
  • 返回$map,使用$mergeObjects合并当前对象和time字段
  {
    $addFields: {
      mcq: {
        $map: {
          input: "$mcq",
          as: "m",
          in: {
            $mergeObjects: [
              "$$m",
              {
                time: {
                  $reduce: {
                    input: "$activity",
                    initialValue: "$$m.time",
                    in: {
                      $cond: [{ $eq: ["$$this.id", "$$m.id"] }, "$$this.time", "$$value"]
                    }
                  }
                }
              }
            ]
          }
        }
      }
    }
  }

Playground

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-03
    • 1970-01-01
    • 2014-12-01
    • 1970-01-01
    • 2023-03-07
    • 2013-11-26
    • 1970-01-01
    相关资源
    最近更新 更多