-
Type:
Task
-
Resolution: Done
-
Priority:
Major - P3
-
Affects Version/s: 2.11.0
-
Component/s: Query Operations
-
None
-
Environment:Windows 7 64-bit, Java 8 Oracle JVM
-
None
-
None
-
None
-
None
-
None
-
None
-
None
Copied from the StackOverflow question I created:
I have not been able to make a query work when using sort. I expect the results of a query to be exactly the same as if I were not using sort, except the results should come in sorted, of course, but what happens is that when using sort I get nothing back.
Here's a complete example to reproduce the problem:
DB db = fongo.getDB( "something" ); DBCollection collection = db.getCollection( "what" ); collection.insert( new BasicDBObject( "hello", 4 ) ); collection.insert( new BasicDBObject( "hello", 2 ) ); collection.insert( new BasicDBObject( "hello", 1 ) ); collection.insert( new BasicDBObject( "hello", 3 ) ); final DBCursor sorted = collection .find( new BasicDBObject( "hello", new BasicDBObject( "$exists", true ) ) ) .sort( new BasicDBObject( "hello", 1 ) ) .limit( 10 ); final DBCursor notSorted = collection .find( new BasicDBObject( "hello", new BasicDBObject( "$exists", true ) ) ) .limit( 10 ); // both asserts below work! assertThat( notSorted.size(), is( 4 ) ); assertThat( sorted.size(), is( 4 ) ); List<DBObject> notSortedAsList = notSorted.toArray(); List<DBObject> sortedAsList = sorted.toArray(); assertThat( notSortedAsList.size(), is( 4 ) ); assertThat( sortedAsList.size(), is( 4 ) ); // << BREAKS HERE!!!! assertThat( sortedAsList.stream().map( obj -> obj.get( "hello" ) ) .collect( Collectors.toList() ), is( Arrays.asList( 1, 2, 3, 4 ) ) );
As you can see, the notSortedAsList list contains 4 elements, as expected, but sortedAsList is empty!! The only difference being that the latter was created from a query containing sort.
Unless I am doing something wrong, it seems that this could be a bug in the MongoDB Java driver, even though it could also be related to Fongo as I am using it to test this.
Any ideas about what's happening??
EDIT
This is what is generated by the query containing sort shown above:
find({ "query" : { "hello" : { "$exists" : true}} , "orderby" : { "hello" : 1}}, null).skip(0).limit(10)
Without sort, the query looks like this:
find({ "hello" : { "$exists" : true}}, null).skip(0).limit(10)
I have also tried doing the following query:
final DBCursor sorted = collection .find( new BasicDBObject( "hello", new BasicDBObject( "$exists", true ) ) ) .addSpecial( "$orderby", new BasicDBObject( "hello", 1 ) ) .limit( 10 );
The generated query then is:
find({ "$orderby" : { "hello" : 1} , "query" : { "hello" : { "$exists" : true}}}, null).skip(0).limit(10)
Both have the same result, though the first uses orderby and the second uses $orderby (as suggested here: http://docs.mongodb.org/manual/reference/operator/meta/orderby/#op._S_orderby)