MongoDB: How do I query for the number of elements in an array of documents/dictionaries?

走远了吗. 提交于 2019-12-13 04:13:40

问题


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.


回答1:


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" }
      } 
    }
])



回答2:


Here you can find use of $group along with and find size of array

Ref:- https://docs.mongodb.com/manual/reference/operator/aggregation/group/



来源:https://stackoverflow.com/questions/49142110/mongodb-how-do-i-query-for-the-number-of-elements-in-an-array-of-documents-dict

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!