简体   繁体   English

与mongo db不同的值?

[英]Distinct values from mongo db?

I want to get unique values from mongo db. 我想从mongo db获取唯一值。 I have tried a lot but could not found the correct solution. 我已经尝试了很多,但是找不到正确的解决方案。 this is how i am fetching values from mongo db. 这就是我从mongo db获取值的方式。

    Mongo mongo = new Mongo("localhost", 27017);
    DB db = mongo.getDB("test");

    DBCollection collection = db.getCollection("testCollection");


    String hopKey = UUID.randomUUID().toString();           

    System.out.println("BasicDBObject example...");
    BasicDBObject document = new BasicDBObject();
    document.put("host", "http://localhost:5050");
    document.put("key", hopKey);
    document.put("appName", "BANK2");
    document.put("userId", "xym@gmail.com");         
    //collection.insert(document);

    List cursorDoc = collection.distinct("appName");
    System.out.println(cursorDoc.get(0).toString());

This is giving me the list size as 2 which is correct. 这使我的列表大小为2,这是正确的。 but how can i get all the row values for these 2 unique values. 但是我如何获得这2个唯一值的所有行值。 Because i need to use all values of these two unique in jsp file. 因为我需要在jsp文件中使用这两个唯一的所有值。 Please help me. 请帮我。

collection.distinct('appName')

will give you all the different values in your collection that exist for that particular fieldName. 将为您提供集合中针对特定fieldName存在的所有不同值。 If you know that all documents have some kind of value there, then you can just do 如果您知道所有文档在那里都具有某种价值,那么您可以

collection.find({})

If you are not sure that the field exists for each document, then you only want to documents where that field exists 如果不确定每个文档都存在该字段,则只想记录该字段所在的位置

collection.find({'appName' : {'$exists' :true}})

That will get you all the documents that have the field 'appName' defined and the value will be one of the two values that you are expecting from your collection.distinct('appName') command 这将为您提供所有已定义“ appName”字段的文档,并且该值将是您希望从collection.distinct('appName')命令获得的两个值之一。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM