我不太清楚你是怎麼想的格式,BU可以試試這些辦法作爲一個日期或小時。
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"]
}]
}
}
}
])
對於蒙戈< 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"]
}]
}
}
}
])
你嘗試過什麼? –
結構非常差。 timeLogs總是包含2個條目? –
是的,我試過$ subract(它提供了毫秒),是的timeLog總是有2個條目。 – hardy