从mongo数据库中检索_ids

时间:2013-06-19 20:36:56

标签: java mongodb database

我正在尝试使用Java从数据库中获取mongo“_ids”列表。我不需要数据库中任何其他对象的部分,只需要“_id”。

这就是我现在正在做的事情:

// Another method queries for all objects of a certain type within the database.
Collection<MyObject> thingies = this.getMyObjects();

Collection<String> ids = new LinkedList<String>();
for (MyObject thingy : thingies) {
  ids.add(thingy.getGuid());
}

这看起来非常低效,但是...有没有办法只查询mongo某些类型的对象,只返回它们的“_ids”而不必重新组合整个对象并提取它?

谢谢!

1 个答案:

答案 0 :(得分:1)

find()方法有一个重载,您可以在其中传递要从查询中检索的键或您不想要的键。

所以你可以试试这个:

BasicDBObject qyery = new BasicDBObject("someKey","someValue");
BasicDBObject keys = new BasicDBObject("_id", 1);
DBCursor cursor = collection.find(query, keys);