tags:

views:

34

answers:

1

What is the equivalent cde in Java:

var result = collectionName.findOne()
println(result.get("name").toString)

To elaborate, This is my sample db:

{ "_id" : ObjectId("4ca039f7a5b75ab98a44b149"), "name" : "kaustubh", "country" : "india" }
{ "_id" : ObjectId("4ca03a85a12344a5e47bcc5c"), "name" : "rahul", "country" : "pakistan" }
{ "_id" : ObjectId("4ca03a9ea12344a5e47bcc5d"), "name" : "swapnil", "country" : "lanka" }
{ "_id" : ObjectId("4ca03b19a12344a5e47bcc5e"), "name" : "sagar", "country" : "nepal" }

i am running the following query on it:

query.put("country", "india");
  DBCursor cursor = collection.find(query);
  while (cursor.hasNext()) {
    System.out.println(cursor.next());
}

that prints:

{ "_id" : { "$oid" : "4ca04b6b37a85ab92557218a"} , "name" : "kaustubh" , "country" : "india"}

as many times as the pair exists in the collection.

how do I formulate a query to get all the names, once and get the count for them.I read the docs, and didnt stumble upon any way to do it.

A: 

Try this

query.put("name", "kaustubh");
DBObject myDoc = collection.findOne(query);
System.out.println(myDoc);

Cheers

Ramesh Vel
using collection.distinct("country", new BasicDBObject "name", "kaustubh") worked:)
Kaustubh P
Distinct works in a different way, first it ll identify all the items and will return one of it. But findOne stops execution when the first item matches.. Performance is lot better compared to distinct... Distinct is not good for your requirement.
Ramesh Vel
I understand that I incorrectly asked the question. I edited it now, for which distinct() is necessary! I then store the distinct values in a List, and the count for each value in another. Thanks for answering my queries!
Kaustubh P