本文介绍了查找用户在mongoDB中花费的总时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个mongodb,其结构如下:
I have a mongodb with the structure as below:
|User |Location |TimeOfVisit
|U1. |Cafeteria.|ISODate("2018-12-27T09:09:08.688Z")
|U2. |Reception.|ISODate("2018-12-27T09:12:45.688Z")
|U1. |Cafeteria.|ISODate("2018-12-27T09:45:38.688Z")
|U1. |Cafeteria.|ISODate("2018-12-27T09:47:38.688Z")
我需要找到用户在任何特定位置所花费的总时间.我已经阅读了多个博客,但尚未找到任何具体答案.我有以下内容:
I need to find the total amount of time taken by an user in any particular location. I have read across multiple blogs and yet to find any concrete answer. I have the following:
aggregate([
{
"$match": {
"User": {
"$eq": req.query.User
}
}
},
{
"$group": {
"_id": "$location",
"totalMiniutes": {
<<Get the time>>
}
}
}
推荐答案
您可以从TimeOfVisit
字段中找到timeOfDay
,然后使用"> $sum
以获取总数
You can find the timeOfDay
from the TimeOfVisit
field and then use $sum
to get the total count
db.collection.aggregate([
{ "$match": { "User": req.query.User }},
{ "$addFields": {
"timeOfDay": {
"$mod": [
{ "$toLong": "$TimeOfVisit" },
1000*60*60*24
]
}
}},
{ "$group": {
"_id": "$location",
"totalTimeInMilliseconds": { "$sum": "$timeOfDay" }
}}
])
[
{
"_id": "Reception",
"totalTimeInMilliseconds": 33165688
},
{
"_id": "Cafeteria",
"totalTimeInMilliseconds": 98846064
}
]
您可以将其进一步划分为天,小时,分钟或秒数
You can further divide it to get the days, hours, minutes or seconds
1 hour = 60 minutes = 60 × 60 seconds = 3600 seconds = 3600 × 1000 milliseconds = 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 及更高版本
For the mongodb 4.0 and above
db.collection.aggregate([
{ "$addFields": {
"timeOfDay": {
"$mod": [
{ "$toLong": "$TimeOfVisit" },
1000 * 60 * 60 * 24
]
}
}},
{ "$group": {
"_id": "$location",
"totalTimeInMiniutes": {
"$sum": { "$divide": ["$timeOfDay", 60 × 1000] }
}
}}
])
这篇关于查找用户在mongoDB中花费的总时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!