【问题标题】:Retrieve _ids from mongo database从 mongo 数据库中检索 _ids
【发布时间】:2013-06-16 13:18:12
【问题描述】:

我正在尝试使用 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”而无需重新组装整个对象并提取它?

谢谢!

【问题讨论】:

标签: java mongodb database


【解决方案1】:

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

所以你可以试试这个:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-19
    • 1970-01-01
    • 2012-09-09
    • 2019-11-19
    • 2018-12-31
    相关资源
    最近更新 更多