6
我使用嗎啡Java驅動程序,用於查詢包含以下形式的集合的MongoDB:查詢的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項!
真正讓我困惑的是,如果我使用.find代替.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
爲什麼該過濾器不使用不同方法 - 工作時呼叫?
是的,這是我目前使用的解決方法。但我相信我應該能夠添加一個查詢,在查出不同的值之前對結果進行排序。 – aksamit
如果你想在mongodb級別進行排序,如果你正在進行限制 – nightograph