您可以
timeOfDay从
TimeOfVisit字段中找到,然后使用
$sum
来获取总数
db.collection.aggregate([ { "$match": { "User": req.query.User }}, { "$addFields": { "timeOfDay": { "$mod": [ { "$toLong": "$TimeOfVisit" }, 1000*60*60*24 ] } }}, { "$group": { "_id": "$location", "totalTimeInMilliseconds": { "$sum": "$timeOfDay" } }}])Output
[ { "_id": "Reception", "totalTimeInMilliseconds": 33165688 }, { "_id": "Cafeteria", "totalTimeInMilliseconds": 98846064 }]您可以将其进一步划分以获取天,小时,分钟或秒
1 hour = 60 minutes = 60 × 60 seconds = 3600 seconds = 3600 × 1000milliseconds = 3,600,000 ms.
db.collection.aggregate([ { "$addFields": { "timeOfDay": { "$mod": [ { "$subtract": [ "$TimeOfVisit", Date(0) ] }, 1000 * 60 * 60 * 24 ] } }}, { "$group": { "_id": "$location", "totalTimeInMiniutes": { "$sum": { "$divide": ["$timeOfDay", 60 × 1000] } } }}])对于mongodb 4.0 及更高版本
db.collection.aggregate([ { "$addFields": { "timeOfDay": { "$mod": [ { "$toLong": "$TimeOfVisit" }, 1000 * 60 * 60 * 24 ] } }}, { "$group": { "_id": "$location", "totalTimeInMiniutes": { "$sum": { "$divide": ["$timeOfDay", 60 × 1000] } } }}])


