Mongodb, Group By Datediff And Getting Hour
I m actually developping an application and I need to get some informations from my database : I have a traitement model in which I got a user, The traitement model has start date
Solution 1:
From what I understood in your question (you actually need to provide a sample couple of documents with your schema) if your Traitement
model has the following structure, for instance:
/* 0 */
{
"_id" : 1,
"user" : "abc",
"dateEntre" : ISODate("2014-03-01T08:00:00.000Z"),
"dateSortie" : ISODate("2014-03-01T13:00:00.000Z")
}
/* 1 */
{
"_id" : 2,
"user" : "jkl",
"dateEntre" : ISODate("2014-03-01T08:00:00.000Z"),
"dateSortie" : ISODate("2014-03-01T10:30:00.000Z")
}
/* 2 */
{
"_id" : 3,
"user" : "jkl",
"dateEntre" : ISODate("2014-03-01T12:00:00.000Z"),
"dateSortie" : ISODate("2014-03-01T18:00:00.000Z")
}
Your aggregation framework would have a single $project
pipeline operation where you get the difference between the two dates by using the $subtract
operator and then transform that date difference in milliseconds to hours by using the $divide
operator. The last stage in your pipeline will be to use the $group
operator to group the documents from the previous pipeline and $sum
the hours in date difference:
Traitement.aggregate([
{
$project: {
user: 1,
dateDifference: {
$divide: [{
$subtract: [ "$dateSortie", "$dateEntre" ]
}, 1000*60*60
]
}
}
},
{
$group: {
_id: "$user",
total : {
$sum : "$dateDifference"
}
}
}
])
Results:
/* 0 */
{
"result" : [
{
"_id" : "jkl",
"total" : 8.5
},
{
"_id" : "abc",
"total" : 5
}
],
"ok" : 1
}
Post a Comment for "Mongodb, Group By Datediff And Getting Hour"