Mongo DB using group and sortbycount

Viewed 104

I have a collection that I want to get the most users logged in per computer. When I run this:

    db.pdqLT_collection.aggregate({'$group': {'_id': '$Computer Name'}})
{ "_id" : "dw-sql" }
{ "_id" : "WCHOF6553" }
{ "_id" : "WCHOFC862" }

When I run this:

    db.pdqLT_collection.aggregate({"$sortByCount": "$Username"})
{ "_id" : "", "count" : 948 }
{ "_id" : "chiconference", "count" : 70 }
{ "_id" : "Administrator", "count" : 43 }

I'm trying to combine it so I can get the total count of the different users who logged in per computer. I tried this:

    db.pdqLT_collection.aggregate([{'$group': {'_id': '$Computer Name', "$sortByCount": "$Username"}} ])    
[js] uncaught exception: Error: command failed: {
        "ok" : 0,
        "errmsg" : "The field '$sortByCount' must be an accumulator object"

And tried this:

    db.pdqLT_collection.aggregate([{'$group': {'_id': '$Computer Name'}, "$sortByCount": "$Username"} ])
uncaught exception: Error: command failed: {
        "ok" : 0,
        "errmsg" : "A pipeline stage specification object must contain exactly one field."

The database consist of info like so, the username can change per day depending on who logged in that day:

{
    "_id" : ObjectId("5f63931dc8b8b56ca2f625c2"),
    "Computer Name" : "WCHOFFC26",
    "Computer Model" : "Precision 7820 Tower",
    "Username" : "tlang",
    "Computer ID" : "918",
    "Computer Serial Number" : "9KZSHQ2",
    "TS" : ISODate("2020-09-17T16:47:25.591Z")
}

Does anyone know what I'm doing wrong here?

So I'm getting closer I have the unique users who logged in but not the count of how many times the user logged in. What I'm doing is getting info of all PC's and who logged in that day. What I need is who logged in the most for that month.

db.pdqLT_collection.aggregate([ {'$group': {'_id': '$Computer Name', 'user': {"$addToSet": '$Username'}}}])
{ "_id" : "OCHOF792E", "user" : [ "lcooper" ] }
{ "_id" : "OCHOF77FA", "user" : [ "dcertoma" ] }
{ "_id" : "NJOF1497", "user" : [ "Administrator", "baumat" ] }
0 Answers
Related