Java MongoDB 3.0 driver query distinct without filter

后端 未结 2 1203
北荒
北荒 2021-01-13 08:23

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

I am attempting to query unique categories records from a locations

2条回答
  •  感动是毒
    2021-01-13 08:49

    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 c = 
       db.getCollection("locations").distinct("categories", String.class).iterator();
    

    or all numbers:

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

    You can still do:

    MongoCursor 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.

    提交回复
    热议问题