JVK
JVK

Reputation: 3912

Retrieving recent data with distinct column value - mongoid + rails4

I have a kevent collection on mongodb that looks like:

_id,                user_id     action          created_at
43gy5235rwedwe      11          logout          2014-05-30 04:01:32 +0000
563gy5wwwedwex      11          running         2014-05-30 04:01:28 +0000
77gy5235rwedwe      26          logout          2014-05-30 04:01:22 +0000
3gy5235rwed65e      11          create          2014-05-30 04:01:20 +0000
4dgy5er35rwcwe      11          upgrade         2014-05-30 04:01:18 +0000
df5gy5s35rwwwd      43          poked           2014-05-30 04:00:32 +0000
fggy5235r322fs      29          login           2014-05-30 03:01:31 +0000
bhgy5235rwedfs      43          login           2014-05-30 03:01:30 +0000
ftweerw35rwedw      11          jumped          2014-05-30 04:01:29 +0000
we2y5s35rwedqq      12          created         2014-05-30 02:01:28 +0000
36gy5sa5rwesad      26          login           2014-05-30 01:01:27 +0000
36q4sa5rwesadw      11          login           2014-05-30 00:01:26 +0000

I am using mongoid (in rails 4) to retrieve recent three actions of distinct users. So the result should look like this:

_id,                user_id     action          created_at
43gy5235rwedwe      11          logout          2014-05-30 04:01:32 +0000
77gy5235rwedwe      26          logout          2014-05-30 04:01:22 +0000
df5gy5s35rwwwd      43          poked           2014-05-30 04:00:32 +0000

How to get that using mongoid?

Upvotes: 0

Views: 59

Answers (1)

Fmontes86
Fmontes86

Reputation: 11

Try this out!

Sql:

SELECT *
FROM users
WHERE status = "A"
AND age = 50

Mongo:

db.users.find(
    { status: "A",
      age: 50 }
)

In your case you can do something like this:

User.any_of("$and" => [{action: "logout", action: "poked"}])

You can see every comparison to SQL to Mongo here

Upvotes: 1

Related Questions