本文介绍了MongoDB:如何查询一系列文档/词典中的元素数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个文档,其中包含字典列表,这些字典显示用户的登录日期和会话ID.如何使用MongoDB Shell查询总登录数?
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 }我无法弄清楚我在做什么错.如果我在列表的开头算空括号,结果应该返回15.
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.
推荐答案您不必在这里使用$ unwind,只需使用 $ size 运算符
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" } } } ])更多推荐
MongoDB:如何查询一系列文档/词典中的元素数量?
发布评论