查询MongoDB以获取有序的不同值
我使用Morphia Java驱动程序查询包含以下格式集合的MongoDB:
I am using Morphia Java driver for querying a MongoDB that contains a collection of the following form:
MyCollection {
TypeA
TypeB
}
我想检索所有不同的值我使用以下代码执行TypeB:
I want to retrieve all distinct values of TypeB which I do using the following code:
DBCollection myCol = getDatastore().getCollection(MyCollection.class);
List typeBs = myCol.distinct("TypeB");
上面的代码按预期工作,但不同值的列表当然没有排序。
Above code works as expected, but list of distinct values is of course not sorted.
我已经尝试了以下代码:
I have experimented with the following code:
DBCollection myCol = getDatastore().getCollection(MyCollection.class);
DBObject orderBy = new BasicDBObject("$orderby", new BasicDBObject("TypeB", 1);
List typeBs = myCol.distinct("TypeB", orderBy);
但在这种情况下,清单是空的,我的假设在哪里错了?
But in this case the list is empty, where are my assumptions wrong?
UPDATE
通过使用CLI我发现以下查询返回了预期结果:
By using the CLI I found out that the following query returned the expected result:
> db.mycollection.find({$query : {}, $orderby : { TypeB : 1 }})
所以我相应调整了我的代码:
So I adjusted my code accordingly:
DBCollection myCol = getDatastore().getCollection(MyCollection.class);
BasicDBObject ascending = new BasicDBObject("TypeB", 1);
BasicDBObject filter = new BasicDBObject();
filter.put("$query", new BasicDBObject());
filter.put("$orderby", ascending);
List typeBs = myCol.distinct("TypeB", filter);
结果仍包含0个条目!
真正的结果我同意融合是相同的查询工作,如果我使用.find而不是.distinct:
What really makes me confused is that the same query works if I use .find instead of .distinct:
DBCollection myCol = getDatastore().getCollection(MyCollection.class);
BasicDBObject ascending = new BasicDBObject("TypeB", 1);
BasicDBObject filter = new BasicDBObject();
filter.put("$query", new BasicDBObject());
filter.put("$orderby", ascending);
myCol.find(filter).hasNext(); <-- Evaluates to TRUE
为什么过滤器在使用 distinct 方法调用?
Why is it that the filter doesn't work when using the distinct method-call?
DBCollection.distinct()的第二个DBObject参数是查询对象,用于定义匹配条件。要对列表进行排序,您可以使用:
the second DBObject parameter of DBCollection.distinct() is a query object, used to define the matching criteria. To sort the list distincts you can use:
List typeBs = myCol.distinct("TypeB");
java.util.Collections.sort(typeBs);