【问题标题】:Subtract time from array to an array MongoDB从数组减去时间到数组MongoDB
【发布时间】:2020-12-22 08:29:42
【问题描述】:

我有这样的数据

"delivery": [{
        "status": "Not Started",
        "createdAt": {
            "$date": "2020-12-21T03:50:33.877Z"
        },
        "updatedAt": {
            "$date": "2020-12-21T03:50:33.877Z"
        }
    }, {
        "status": "Accepted",
        "updatedAt": {
            "$date": "2020-12-21T03:51:20.915Z"
        },
        "createdAt": {
            "$date": "2020-12-21T03:51:20.915Z"
        }
    }, {
        "status": "Ongoing",
        "updatedAt": {
            "$date": "2020-12-21T03:52:40.087Z"
        },
        "createdAt": {
            "$date": "2020-12-21T03:52:40.087Z"
        }
    }, {
        "status": "Ended",
        "updatedAt": {
            "$date": "2020-12-21T03:52:40.087Z"
        },
        "createdAt": {
            "$date": "2020-12-21T04:00:40.087Z"
        }

我想获取从 Not StartedAccepted 以及从 OngoingEnded 的时间差。我遇到了一个错误cant $subtract aarray from a array我希望得到两个不同数组之间的差异。

db.deliveries.aggregate([
    { 
        $project: 
        { 
            "delivery.createdAt": 1,
            "delivery.updatedAt": 1
        } 
    },
    { 
        $addFields: {
            difference: {
                $divide: [{$subtract: ["$delivery.updatedAt", "$delivery.createdAt"]}, 3600000]
            }
        }       
    },
])

预期输出:

{
    "status": "Not Started",
    "createdAt": {
        "$date": "2020-12-21T03:50:33.877Z"
   },
   "updatedAt": {
        "$date": "2020-12-21T03:50:33.877Z"
    }
}, {
    "status": "Accepted",
    "updatedAt": {
        "$date": "2020-12-21T03:51:20.915Z"
    },
    "createdAt": {
        "$date": "2020-12-21T03:51:20.915Z"
    }
},
difference: 0.013066111111111112



{
    "status": "Ongoing",
    "updatedAt": {
        "$date": "2020-12-21T03:52:40.087Z"
    },
    "createdAt": {
        "$date": "2020-12-21T03:52:40.087Z"
    }
}, {
    "status": "Ended",
    "updatedAt": {
        "$date": "2020-12-21T03:52:40.087Z"
    },
    "createdAt": {
        "$date": "2020-12-21T04:00:40.087Z"
    },
 difference: 0.08 //sample computation

我想计算从 Not Started(createdAt) 到 Accepted(updatedAt) 的差异。并得到从 **Ongoing(createdAt) 到 Ended(updatedAt) 的区别。

【问题讨论】:

    标签: mongodb mongodb-query aggregation-framework


    【解决方案1】:

    您可以通过 $addFields 和 $cond 找出开始和结束时间。然后计算差值,

    这是Mongo Playground供您参考。

    【讨论】:

    • 嗨,我的意思是。从状态:未开始,计算到状态:接受的时间差。
    • 更新了解决方案。请你看看现在好看吗? :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-20
    • 1970-01-01
    • 2012-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多