我想从MongoDB中的结帐日期减去签入日期
我该怎么做?
来自MongoDB的数据: -
"timeLogs" : [
{
"type" : "chekin",
"date" : ISODate("2017-05-02T05:10:00.000Z"),
"_id" : ObjectId("590822c66216cf3864740e3d")
},
{
"type" : "checkout",
"date" : ISODate("2017-05-02T14:10:00.000Z"),
"_id" : ObjectId("59088037feb56c0fcd60a090")
}
]
任何帮助都会得到满足。
答案 0 :(得分:0)
我不太确定您希望格式如何,您可以尝试将这些选项作为日期或小时。
db.getCollection('Date').aggregate([
{
$project: {
_id: "$_id",
startDate: {
$arrayElemAt: ["$timeLogs", 0]
},
endDate: {
$arrayElemAt: ["$timeLogs", 1]
}
}
}, {
$project: {
timeDiff: {
$divide: [{
$subtract: ["$endDate.date", "$startDate.date"]
}, 1000 * 60 * 60]
}
}
}
])
或作为日期
db.getCollection('sample date').aggregate([
{
$project: {
_id: "$_id",
startDate: {
$arrayElemAt: ["$timeLogs", 0]
},
endDate: {
$arrayElemAt: ["$timeLogs", 1]
}
}
}, {
$project: {
timeDiff: {
$add: [new Date(0), {
$subtract: ["$endDate.date", "$startDate.date"]
}]
}
}
}
])
对于mongo< 3.2
db.getCollection('Date').aggregate([
{
$unwind: "$timeLogs"
},
{
$group: {
_id: "$_id",
startDate: {
$first: "$timeLogs"
},
endDate: {
$last: "$timeLogs"
}
}
}, {
$project: {
timeDiff: {
$add: [new Date(0), {
$subtract: ["$endDate.date", "$startDate.date"]
}]
}
}
}
])