-->

查询的MongoDB有序不同的值(Query MongoDB for ordered distinc

2019-07-31 16:32发布

我使用吗啡Java驱动程序,用于查询包含以下形式的集合的MongoDB:

MyCollection {
   TypeA
   TypeB
}

我想找回这一点我用下面的代码的TypeB的所有不同值:

DBCollection myCol = getDatastore().getCollection(MyCollection.class);
List typeBs = myCol.distinct("TypeB");

上面的代码工作正常,但不同值的列表当然是没有排序。

我已经尝试用下面的代码:

DBCollection myCol = getDatastore().getCollection(MyCollection.class);
DBObject orderBy = new BasicDBObject("$orderby", new BasicDBObject("TypeB", 1);
List typeBs = myCol.distinct("TypeB", orderBy);

但是,在这种情况下,该列表是空的,到哪里都是我的假设错了吗?

UPDATE

通过使用CLI我发现下面的查询返回预期的结果:

> db.mycollection.find({$query : {}, $orderby : { TypeB : 1 }})

所以我相应调整我的代码:

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项!

真正让我困惑的是,如果我使用的.distinct .find而不是相同的查询工作:

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

为什么是它使用不同的方法调用,当过滤器不起作用?

Answer 1:

DBCollection.distinct的第二DBOBJECT参数()是一个查询对象,用于定义匹配条件。 为了您可以使用列表排序distincts:

List typeBs = myCol.distinct("TypeB");
java.util.Collections.sort(typeBs);


文章来源: Query MongoDB for ordered distinct values