如何从java中的Mongo子文档中获取特定数据?

时间:2017-10-09 12:56:05

标签: java mongodb

我试图获取mongo文档中特定列值的数据,但显示整个数据。

以下是mongo文件:

{
    "_id" : ObjectId("59db2321811a592384865711"),
    "User_ID" : "demo",
    "Project_ID" : "demo-1",
    "Project_Information" : {
        "Project_Description" : "Sample",
        "Primary_Building_Type" : "Office",
        "State" : "AR",
        "Analysis_Type" : "1",
        "Project_Billing_Number" : "WY",
        "Country" : "USA",
        "Climate_Zone" : "3A",
        "Zip_Code" : "71611"
        "City" : "WA",
        "Units" : "IP"
    }
}

我想获取以下输出:

[
    {
        "User_ID": "demo",
        "Project_Description": "Sample"
}]

我尝试过使用dot:Project_Information.Project_Description。代码如下:

public Object[] addDemo1(String User_ID) throws Exception {
    DB db = ConnectToDB.getConnection();
    Properties prop = new Properties();
    InputStream input = null;
    input = GetProjectStatus.class.getClassLoader().getResourceAsStream("config.properties");
    prop.load(input);
    String col = prop.getProperty("COLLECTION_PI");
    System.out.println("data is.." + col);
    DBCollection collection = db.getCollection(col);
    BasicDBObject obj = new BasicDBObject();
    BasicDBObject fields = new BasicDBObject();
    BasicDBObject fields2 = new BasicDBObject();
    List<DBObject> obj1 = null;
    if (User_ID != null && !User_ID.equals("") && User_ID.length() > 0) {
        obj.put("User_ID", User_ID);
        fields.put("_id", 0);
        fields.put("User_ID", 1);
        fields.put("Project_ID", 1);
        fields.append("Project_Information.Project_Description", "Project_Description");
        BasicDBObject fields1 = new BasicDBObject();
        fields1.put("User_ID", User_ID);
    }
    DBCursor cursor = collection.find(obj, fields);
    System.out.println("count  is:" + cursor.count());
    obj1 = cursor.toArray();
    System.out.println("" + obj1);
    cursor.close();
    db.getMongo().close();
    return obj1.toArray();

}

但它显示Project_Information的整个结构。

请说明如何实现这一目标。谢谢你的帮助。

2 个答案:

答案 0 :(得分:0)

Java库不允许您使用dot直接访问。

他们建立了getter和setter方法。

您尚未提及您正在使用的软件包。

这是您需要的查询:

db.mycol.find({},{User_ID:1,"Project_Information.Project_Description":1})

它会给出:

{ "_id" : ObjectId("59db2321811a592384865711"),
    "User_ID" : "demo",
    "Project_Information" : { "Project_Description" : "Sample" }
}

您必须以您的包接受的任何格式转换查询。

这是一个教程: https://www.mongodb.com/blog/post/getting-started-with-mongodb-and-java-part-i

答案 1 :(得分:0)

使用2.x MongoDB Java驱动程序

以下是使用MongoDB 2.x Java驱动程序的示例:

DBCollection collection = mongoClient.getDB("stackoverflow").getCollection("demo");

BasicDBObject filter = new BasicDBObject();
BasicDBObject projection = new BasicDBObject();

// project on "Project_Information.Project_Description"
projection.put("Project_Information.Project_Description", 1);

DBCursor documents = collection.find(filter, projection);

for (DBObject document : documents) {
    // the response contains a sub document under the key: "Project_Information"
    DBObject projectInformation = (DBObject) document.get("Project_Information");
    // the "Project_Description" is in this sub document
    String projectDescription = (String) projectInformation.get("Project_Description");

    // prints "Sample"
    System.out.println(projectDescription);

    // to return this single String value in an Object[] (as implied by your OP) just do create the Object[] like this and then return it ...
    Object[] r = new Object[] {projectDescription};

    // prints the entire projected document e.g. 
    // { "_id" : { "$oid" : "59db2321811a592384865711" }, "Project_Information" : { "Project_Description" : "Sample" } }
    System.out.println(document.toString());
}

使用3.x MongoDB Java驱动程序

以下是使用MongoDB 3.x Java驱动程序的示例:

    // this finds all documents in a given collection (note: no parameter supplied to the find() call) 
    // and for each document it projects on Project_Information.Project_Description
    FindIterable<Document> documents =
            mongoClient.getDatabase("...").getCollection("...")
               .find()
               // for each attrbute you want to project you must include its dot notation path and the value 1 ... 
               // this is the equivalent of specifying {'Project_Information.Project_Description': 1} in the MongoDB shell
               .projection(new Document("Project_Information.Project_Description", 1));

    for (Document document : documents) {
        // the response contains a sub document under the key: "Project_Information"
        Document projectInformation = (Document) document.get("Project_Information");
        // the "Project_Description" is in this sub document
        String projectDescription = projectInformation.getString("Project_Description");

        // prints "Sample"
        System.out.println(projectDescription);

        // to return this single String value in an Object[] (as implied by your OP) just do create the Object[] like this and then return it ...
        Object[] r = new Object[] {projectDescription};

        // prints the entire projected document e.g. { "_id" : { "$oid" : "59db2321811a592384865711" }, "Project_Information" : { "Project_Description" : "Sample" } }
        System.out.println(document.toJson());
    }