Java相当于mongodb中的scala查询

时间:2010-09-27 07:50:24

标签: java mongodb

Java中等效的cde是什么:

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

详细说明,这是我的样本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" }

我正在运行以下查询:

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

打印:

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

该对集合中存在该对的次数。

如何制定查询以获取所有名称,一次并获得它们的计数。我阅读文档,并没有偶然发现任何方法。

1 个答案:

答案 0 :(得分:0)

试试这个

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