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

Vincent Cantin picture Vincent Cantin · Apr 17, 2013 · Viewed 13k times · Source

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) ?

Answer

Vladimir Muzhilov picture Vladimir Muzhilov · Apr 17, 2013

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