I have a document that contains a list of dictionaries that show a user's login date and session id. How do I query for the number of total logins using MongoDB shell?
{
"uname": "johndoe",
"loginActivity": [{}, {'date': '01/30/2018 15:52', 'SID': '02fe602a'}, {'date': '01/31/2018 20:32', 'SID': '2358eeea'}, {'date': '01/31/2018 20:06', 'SID': '3d720386'}, {'date': '01/25/2018 01:41', 'SID': '40b30ff2'}, {'date': '01/30/2018 15:55', 'SID': '4a3b9129'}, {'date': '01/31/2018 11:26', 'SID': '50fcead9'}, {'date': '01/29/2018 11:10', 'SID': '5f1f53c6'}, {'date': '01/25/2018 08:49', 'SID': 'a0123437'}, {'date': '01/26/2018 11:03', 'SID': 'c31daaf9'}, {'date': '01/31/2018 17:16', 'SID': 'd4073ae3'}, {'date': '01/25/2018 09:50', 'SID': 'd8cfe718'}, {'date': '01/25/2018 15:29', 'SID': 'e281c0cc'}, {'date': '01/26/2018 09:40', 'SID': 'e75e032a'}, {'date': '01/30/2018 10:26', 'SID': 'f3cc187f'}],
"bytesIn": 18751,
"bytesOut": 8343,
"country": "US",
"state": "California"
}
I have tried this query:
db.user_information.aggregate( [
{ $match: {uname: "johndoe"}},
{ $unwind: "$login_activity"},
{ $group: {_id:0, total:{$sum:1}}}
] )
But I get this result:
{ "_id" : 0, "total" : 1 }
I cannot figure out what I am doing wrong. The result should return 15 if I count the empty bracket in the beginning of the list.
You don't have to use $unwind here, all you need to do is to use $size operator
db.user_information.aggregate([
{ $match: {uname: "johndoe"}},
{ $project: {
uname: 1,
total: { $size: "$loginActivity" }
}
}
])
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments