【发布时间】:2014-04-23 12:43:15
【问题描述】:
使用sort 时,我无法进行查询。我希望查询的结果与我不使用 sort 时的结果完全相同,当然,除了结果应该是排序的,但是当使用 sort 时,我什么也得不到。
这是重现问题的完整示例:
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 ) ) );
如您所见,notSortedAsList 列表包含 4 个元素,正如预期的那样,但 sortedAsList 是空的!唯一的区别是后者是从包含sort 的查询中创建的。
除非我做错了什么,否则这似乎是 MongoDB Java 驱动程序中的一个错误,尽管它也可能与 Fongo 相关,因为我正在使用它来测试它。
对正在发生的事情有什么想法吗??
编辑
这是由上面显示的包含排序的查询生成的:
find({ "query" : { "hello" : { "$exists" : true}} , "orderby" : { "hello" : 1}}, null).skip(0).limit(10)
没有sort,查询看起来像这样:
find({ "hello" : { "$exists" : true}}, null).skip(0).limit(10)
我也尝试过执行以下查询:
final DBCursor sorted = collection
.find( new BasicDBObject( "hello", new BasicDBObject( "$exists", true ) ) )
.addSpecial( "$orderby", new BasicDBObject( "hello", 1 ) )
.limit( 10 );
然后生成的查询是:
find({ "$orderby" : { "hello" : 1} , "query" : { "hello" : { "$exists" : true}}}, null).skip(0).limit(10)
虽然第一个使用orderby,第二个使用$orderby,但两者的结果相同(此处建议:http://docs.mongodb.org/manual/reference/operator/meta/orderby/#op._S_orderby)
【问题讨论】:
-
当您说
assertThat( sorted.size(), is( 4 ) );语句有效时,我会假设sort查询的结果按预期工作。可能是List<DBObject> sortedAsList = sorted.toArray();的问题? -
我也尝试过使用
sorted.iterator(),但这也不会返回任何元素。 -
生成的查询不应该只有
$query而不是query吗???
标签: java mongodb mongo-java fongo