-
Type:
New Feature
-
Resolution: Won't Fix
-
Priority:
Major - P3
-
None
-
Affects Version/s: None
-
Component/s: Querying
-
None
-
None
-
3
-
None
-
None
-
None
-
None
-
None
-
None
If I have a field string like "_id.foo.bar", currently I think there are three ways to find its min/max (Java driver shown here):
Object min = ((BasicDBObject) ((BasicDBObject) myColl.find() .sort(new BasicDBObject("_id.foo.bar", 1)) .limit(1).next().get("_id")).get("foo")).get("bar"); Object min = ((BasicDBObject) ((BasicDBObject) myColl.find() .sort(new BasicDBObject("_id.foo.bar",-1)) .limit(1).next().get("_id")).get("foo")).get("bar");
or
Object min = ((BasicDBObject) ((BasicDBObject) myColl.aggregate( new BasicDBObject("$sort", new BasicDBObject("_id.foo.bar", 1)), new BasicDBObject("$limit", 1)) .results().iterator().next().get("_id")).get("foo")).get("bar"); Object max = ((BasicDBObject) ((BasicDBObject) myColl.aggregate( new BasicDBObject("$sort", new BasicDBObject("_id.foo.bar",-1)), new BasicDBObject("$limit", 1)) .results().iterator().next().get("_id")).get("foo")).get("bar");
or
Object min = myColl.aggregate(new BasicDBObject("$group", new BasicDBObject("_id", null) .append("minVal", new BasicDBObject("$min", "$_id.foo.bar")))) .results().iterator().next().get("minVal"); Object max = myColl.aggregate(new BasicDBObject("$group", new BasicDBObject("_id", null) .append("maxVal", new BasicDBObject("$max", "$_id.foo.bar")))) .results().iterator().next().get("maxVal");
That's a lot of syntactical machinery for a simple concept. And the latter aggregation approach doesn't take advantage of any indexes.
What relief is there for this, even if only syntactic sugar for the above happening behind the scenes?
The distinct() method would seem to provide a template for this:
Object min = myColl.min("_id.foo.bar"); Object max = myColl.max("_id.foo.bar"); // or with a query: Object min = myColl.min("_id.foo.bar", new BasicDBObject("otherField", 6)); Object max = myColl.max("_id.foo.bar", new BasicDBObject("otherField", 6));