如何通过Java在mongoDB中匹配名称来获取元素的ID

时间:2014-08-05 08:53:43

标签: java mongodb

我希望通过Java中的mongoDB中的匹配名称获取ID。

这是我的代码:

MongoClient mongo = new MongoClient();
        DB db = mongo.getDB("test");
        DBCollection groupTable = db.getCollection("Items");

        searchQuery.put("name", "John");

          DBCursor cursor = groupTable.find(searchQuery);
          while (cursor.hasNext()) {
              System.out.println(cursor.next());
          }

但它显示整行包含John的名字,我想要的是ID而不是整个事物。

{"list":[{"timestamp":{"$date":"2014-08-01T08:37:54.058Z"},"name":John,"_id":{"$oid":"53db5045ccf2b2399e0e6128"},"created":{"$date":"2014-08-}

有任何帮助吗? 感谢

1 个答案:

答案 0 :(得分:1)

这很简单,只需选择id ...

while (cursor.hasNext()) {
    System.out.println(cursor.next().get("_id"));
}