简体   繁体   中英

Return attributes from mongodb object- Java driver

I have mongo object like

{
        "name" : "mongo",
        "values" : [
            {
                    "date" : "02-23-2015",
                    "price" : "5"
            },
            {
                    "date" : "02-23-15",
                    "price" : "6"
            },
            {
                    "date" : "02-22-15",
                    "price" : "7"
            }
    ]
}

I am working with Java driver and I am able to extract this object with a query like:

QueryBuilder builder = new QueryBuilder();
DBObject nameQuery = new BasicDBObject("name", "mongo");
builder.and(nameQuery);
DBObject fullQuery = builder.get();

However what I want is to extract all of the price values and I want to store these in an array- right now I am only able to return this entire object..iterating through subsets like this is not explained very well in documentation, one example would be helpful.

Any help would be appreciated.

EDIT: ok now I am able to iterate through the objects in this array but it does not take advantage of mongo built ins and will naturally be slower:

while (curs.hasNext())
    {
        DBObject o = curs.next();
        BasicDBList values = (BasicDBList) o.get("values");
        BasicDBObject[] valuesArray = values.toArray(new BasicDBObject[0]);
        for(BasicDBObject dbObj : valuesArray) {
            name = dbObj.getString("name");
         }
    }

This allows me to extract whatever I want but I know there is a more efficient way. Any help would be great, thanks

I think it should work or it could carry you near of the solution:

    DB db = this.getConnection();
    DBCollection coll = db.getCollection(collection);
    BasicDBObject searchQuery = new BasicDBObject();
    searchQuery.put("name", "mongo");

    cursor = coll.find(searchQuery);

    DBObject resultElement = null;
    List <String> prices = new ArrayList<String>(); 

    while(cursor.hasNext()){
            resultElement = cursor.next();
            prices.add ((String) resultElement.get("values.price"));
    }

Hope it helps.

The DBCollection.find() method takes a second parameter called keys which allows you to define which fields should be included in the result. Use it like this:

collection.find(query, new DBObject("values.price":1);

This will return a document with a values array containing only prices like this:

{
    "values" : [
        {
                "price" : "5"
        },
        {
                "price" : "6"
        },
        {
                "price" : "7"
        }
]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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