Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Distinct() command used with skip() and limit()

I have those items in my MongoDB collection:

{x: 1, y: 60, z:100}
{x: 1, y: 60, z:100}
{x: 1, y: 60, z:100}
{x: 2, y: 60, z:100}
{x: 2, y: 60, z:100}
{x: 3, y: 60, z:100}
{x: 4, y: 60, z:100}
{x: 4, y: 60, z:100}
{x: 5, y: 60, z:100}
{x: 6, y: 60, z:100}
{x: 6, y: 60, z:100}
{x: 6, y: 60, z:100}
{x: 7, y: 60, z:100}
{x: 7, y: 60, z:100}

I want to query the distinct values of x (i.e. [1, 2, 3, 4, 5, 6, 7]) ... but I only want a part of them (similar to what we can obtain with skip(a) and limit(b)).

How do I do that with the java driver of MongoDB (or with spring-data-mongodb if possible) ?

like image 326
Vincent Cantin Avatar asked Apr 17 '13 09:04

Vincent Cantin


People also ask

What is skip and limit?

The limit() function in MongoDB is used to specify the maximum number of results to be returned. Only one parameter is required for this function.to return the number of the desired result. Sometimes it is required to return a certain number of results after a certain number of documents. The skip() can do this job.

How count distinct values in MongoDB?

To count the unique values, use "distinct()" rather than "find()", and "length" rather than "count()". The first argument for "distinct" is the field for which to aggregate distinct values, the second is the conditional statement that specifies which rows to select.


1 Answers

in mongo shell is simple with aggregate framework:

db.collection.aggregate([{$group:{_id:'$x'}}, {$skip:3}, {$limit:5}])

for java look: use aggregation framework in java

like image 183
Vladimir Muzhilov Avatar answered Sep 19 '22 03:09

Vladimir Muzhilov