user2710961
user2710961

Reputation: 69

Max/Min value(without field name) in mongodb with java

I am using the below mentioned MongoDB query in Java to find the maximun value of field price:

DBCursor cursor = coll.find(query,fields).sort(new BasicDBObject("price",1)).limit(1);

fields argument passing to coll.find function here is having the price field only.

So I am getting the output in the form:

{"price" : value}

Is there any way to get value only in the output without the field name and braces etc, so that it can be assigned to a variable or returned to the calling function etc.

Or if there is any other query or mechanism available that I can use for the same purpose.

Pls suggest..

Thanks & Regards

Upvotes: 1

Views: 2256

Answers (2)

Parvin Gasimzade
Parvin Gasimzade

Reputation: 26012

You can get value of price from the DBCursor object as follows.

while (cursor.hasNext()) {
    Double price = (Double) cursor.next().get("price");
}

On the mongo shell you can do it as follows :

db.priceObj.find({},{_id:0, price:1}).sort({price:-1}).limit(1)[0].price

Upvotes: 1

Sammaye
Sammaye

Reputation: 43884

You cannot do this due to the fact that MongoDB communicates using BSON.

A single value like you want would be invalid BSON. It is easy enough to filter it out your side.

Upvotes: 1

Related Questions