Ashok Raj
Ashok Raj

Reputation: 454

how to query group by and distinct with a limit in MongoDB PHP codeigniter?

Is such a operation possible?

sample record:

{ 
 _id: ObjectId("51d6be147483c58419000002"), 
 user: "ashok", 
 action: "login",
 time: 1373027860,
 details: { 
               user_entries:   "blah..blah", 
               url: "web.domain.com" 
                 }
 }

Suppose, i want to group by url visited, for each user, group by url where user = "ashok", limit 10.

I am using AlexBilbie library for MongoDB-Codeigniter (it doesnt have aggregation). so using plain php.
Still even if I could aggregate, how to distinct or limit it?
Any suggestion is welcome.

Upvotes: 0

Views: 2007

Answers (2)

Veeranna Uppari
Veeranna Uppari

Reputation: 11

In the below format you can give a limit:

$this->mongo_db->order_by(array('Student_Name'=>'asc'))->limit(20)->get('mycollection_name'); 

Upvotes: 0

Robert Reiz
Robert Reiz

Reputation: 4433

First of all using group_by and distinct together doesn't make any sense. Either you are using group_by or distinct.

If you want to do some kind of pagination for a grouped query you have to use map and reduce or the aggregation pipeline. In your case the aggregation would look like that.

db.users.aggregate(
  { '$match' => { 'user' => 'ashok' } },
  { '$group' => { '_id' => '$details.url' } },
  { '$skip'  => 0 },
  { '$limit' => 10 }
)

I am using this aggregation feature to display references at VersionEye. The aggregation feature allows to do grouping and paging on db level, that's why it's much faster then other ORM or pagination solutions.

Upvotes: 2

Related Questions