0

我想找出我网站上最活跃的用户。

我有表格的记录

{
    "_id" : "db1855b0-f2f4-44eb-9dbb-81e27780c796",
    "createdAt" : 1360497266621,
    "profile" : { "name" : "test" },
    "services" : { "resume":
        { "loginTokens" : [{
                "token" : "82c01cb8-796a-4765-9366-d07c98c64f4d",
                "when" : 1360497266624
            },
            {
                "token" : "0e4bc0a4-e139-4804-8527-c416fb20f6b1",
                "when" : 1360497474037
            } ]
        },
        "twitter" : {
            "accessToken" : "9314Sj9kKvSyosxTWPY5r57851C2ScZBCe",
            "accessTokenSecret" : "UiDcJfOfjH7g9UiBEOBs",
            "id" : 2933049,
            "screenName" : "testname"
        }
    }
}

我希望能够选择用户并按loginTokens. 其中MySQL会是这样的:

SELECT id, COUNT(logins) AS logins 
FROM users 
GROUP BY id ORDER BY logins DESC

我已经在 querymongo.com 上尝试过,但出现错误(不能使用别名/不能按非列名排序)

Mongo 的方法是什么?

谢谢!

4

2 回答 2

0

Here is an example of what you said using the aggregation framework:

db.users.aggregate([
    {$unwind: '$services.resume.loginTokens'},
    {$group: {_id: '$_id', logins: {$sum: 1}}},
    {$sort: {logins: -1}}
])

This should do the trick.

于 2013-02-18T12:38:05.680 回答
0

我刚刚转换:

SELECT id, COUNT(logins)
FROM users 
GROUP BY id

至:

db.users.group({
    "key": {
        "id": true
    },
    "initial": {
        "countlogins": 0
    },
    "reduce": function(obj, prev) {
        prev.countlogins++;
    }
});

希望这可以帮助

于 2013-02-18T12:13:01.910 回答