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

▼魔方 西西 提交于 2019-12-25 07:35:16

问题


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.


回答1:


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.




回答2:


In the below format you can give a limit:

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


来源:https://stackoverflow.com/questions/17508826/how-to-query-group-by-and-distinct-with-a-limit-in-mongodb-php-codeigniter

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