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

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

问题描述

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

How may I query distinct with the Java MongoDB 3.0 driver?

我试图查询唯一来自MongoDB中 locations 集合的类别记录。在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");

In 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();


推荐答案

为了避免使用不同的强制转换,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天全站免登陆