查询MongoDB以获取有序的不同值 [英] Query MongoDB for ordered distinct values

查看:126
本文介绍了查询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

为什么过滤器在使用<时不起作用? em> 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);

这篇关于查询MongoDB以获取有序的不同值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆