【问题标题】:Mongo DB compare two arrays and add missing elementMongodb比较两个数组并添加缺失元素
【发布时间】:2020-08-08 05:34:33
【问题描述】:

我有一个状态数组,如下所示。

"statuses" : [
        {
            "name" : "In Progress",
            "created_on" : ISODate("2020-04-20T19:00:07.681Z")
        },
        {
            "name" : "Pending",
            "created_on" : ISODate("2020-04-20T19:00:07.886Z")
        },
        {
            "name" : "Viewed",
            "created_on" : ISODate("2020-04-20T20:10:04.733Z")
        },
        {
            "name" : "Initial Viewed",
            "created_on" : ISODate("2020-04-20T20:10:08.468Z")
        },
        {
            "name" : "Opened",
            "created_on" : ISODate("2020-04-21T01:37:08.582Z")
        },
        {
            "name" : "Completed",
            "created_on" : ISODate("2020-04-21T01:48:46.007Z")
        }
    ]

我有另一个数组:

"reference": ['In Progress', 'Pending', 'Sent', 'Initial Viewed', 'Viewed', 'Opened', 'Completed']

当我将我的第一个数组与参考数组进行比较时可以看出,第一个数组中缺少“Sent”,我想用当前的 ISODate() 在我的第一个数组中添加它。而且我希望我的第一个数组与第二个数组的顺序相同。

【问题讨论】:

    标签: mongodb mongodb-query aggregation-framework aggregate


    【解决方案1】:

    通过在reference 上运行$map,您将获得所需的订单。 $filter$arrayElemAt 将让您找到单个匹配元素,$ifNull 可用于在没有匹配项时构建新对象:

    db.collection.aggregate([
        {
            $project: {
                result: {
                    $map: {
                        input: "$reference",
                        as: "ref",
                        in: {
                            $let: {
                                vars: {
                                    matched: {
                                        $arrayElemAt: [ { $filter: { input: "$statuses", cond: { $eq: [ "$$ref", "$$this.name" ] } } }, 0 ]
                                    }
                                },
                                in: {
                                    $ifNull: [ "$$matched", { name: "$$ref", created_on: new Date() } ]
                                }
                            }
                        }
                    }
                }
            }
        }
    ])
    

    Mongo Playground

    【讨论】:

      猜你喜欢
      • 2023-04-04
      • 1970-01-01
      • 2017-08-28
      • 2020-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多