Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mongodb Mongo DB比较两个数组并添加缺少的元素_Mongodb_Mongodb Query_Aggregation Framework_Aggregate - Fatal编程技术网

Mongodb Mongo DB比较两个数组并添加缺少的元素

Mongodb Mongo DB比较两个数组并添加缺少的元素,mongodb,mongodb-query,aggregation-framework,aggregate,Mongodb,Mongodb Query,Aggregation Framework,Aggregate,我有一个状态数组,如下所示 "statuses" : [ { "name" : "In Progress", "created_on" : ISODate("2020-04-20T19:00:07.681Z") }, { "name" : "Pending", "created_on" : ISODate("2020-04-20T19:00:07.886

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

"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']
当我将我的第一个数组与引用数组进行比较时,可以看到,我想用当前ISODate()将第一个数组添加到第一个数组中的第一个数组中缺少“Sent”。我还希望我的第一个数组与第二个数组的顺序相同。

通过运行
reference
可以获得所需的顺序。以及将允许您查找单个匹配元素,并可在不匹配时用于构建新对象:

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() } ]
                            }
                        }
                    }
                }
            }
        }
    }
])