Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
330 views
in Technique[技术] by (71.8m points)

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...