没有过滤器的 Java MongoDB 3.0 驱动程序查询不同 [英] Java MongoDB 3.0 driver query distinct without filter

查看:38
本文介绍了没有过滤器的 Java MongoDB 3.0 驱动程序查询不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 Java MongoDB 3.0 驱动程序查询distinct?

我正在尝试从 MongoDB 的 locations 集合中查询唯一的 categories 记录.在 Mongo shell 中,这很简单:db.locations.distinct("categories");

I am attempting to query unique categories records from a locations collection in MongoDB. In the Mongo shell, this is very simple: db.locations.distinct("categories");

在 Java 中,情况不一样.

In Java, it's not the same.

MongoClient client = new MongoClient();
MongoDatabase db = client.getDatabase("yelp");

//this will not compile, although examples from before 3.0 do it this way
MongoCursor<Document> c = 
    db.getCollection("locations").distinct("categories").iterator();

推荐答案

为了避免对 distinct 进行强制转换,MongoCollection API 允许您为字段提供不同值的预期类型.所以如果你知道它们都是字符串,例如,你可以这样写:

To let you avoid casts for distinct, the MongoCollection API lets you provide the expected type of the distinct values for the field. So if you know they are all strings, for example, you can write:

MongoCursor<String> c = 
   db.getCollection("locations").distinct("categories", String.class).iterator();

或所有数字:

MongoCursor<Number> c = 
   db.getCollection("locations").distinct("categories", Number.class).iterator();

你仍然可以这样做:

MongoCursor<Object> c = 
   db.getCollection("locations").distinct("categories", Object.class).iterator();

如果您不能保证您查询的字段的值的类型.

if you can't guarantee anything about the types of the values for the field you're querying.

这篇关于没有过滤器的 Java MongoDB 3.0 驱动程序查询不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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