如何根据MongoDB中的唯一ID获取多个属性?

时间:2017-04-04 06:55:05

标签: java mongodb

我想从

中检索一个仅列出list<DBObject>的ID和性别的列表
{ "_id": 123 , "gender": m, "occupation": athlete },
{ "_id": 456 , "gender": f, "occupation": basketball },
...

尝试使用以下但无效。将查询作为新的BDObject性别启动:1

dbcollection.distinct("_id", query)

2 个答案:

答案 0 :(得分:0)

db.getCollection('mobiledashboards').find({"_id":ObjectId("58d22f68acfecc105733d56a")})

答案 1 :(得分:0)

&#34; _id&#34;是独一无二的,所以不需要在它上面调用不同的功能

如果你想获得性别和_id的所有文件,你可以通过以下方式实现它

['1489363200000, 97073321, ""',
 '1489449600000, 97138657, ""',
 '1489536000000, 97126694, ""',
 '1489622400000, 98535521, ""',
 '1489708800000, 98482905, ""',
 '1489795200000, 98496091, ""',
 '1489881600000, 98627987, "#2B6A94"',
 '1489968000000, 98798351, ""',
 '1490054400000, 98936652, ""',
 '1490140800000, 99025494, ""',
 '1490227200000, 99208644, ""',
 '1490313600000, 99163634, ""',
 '1490400000000, 99097059, ""',
 '1490486400000, 98986347, "#2B6A94"',
 '1490572800000, 99005343, ""',
 '1490659200000, 99023673, ""',
 '1490745600000, 99084059, ""',
 '1490832000000, 98988641, ""',
 '1490918400000, 99120523, ""',
 '1491004800000, 99058884, ""',
 '1491091200000, 99206546, "#2B6A94"',
 '1491177600000, 99155567, ""',
 '1489363200000,, "#ffffff"',
 '1489449600000,, "#ffffff"',
 '1489536000000,, "#ffffff"',
 '1489622400000,, "#ffffff"',
 '1489708800000,, "#ffffff"',
 '1489795200000,, "#ffffff"',
 '1489881600000,, "#ffffff"',
 '1489968000000,, "#ffffff"',
 '1490054400000,, "#ffffff"',
 '1490140800000,, "#ffffff"',
 '1490227200000,, "#ffffff"',
 '1490313600000,, "#ffffff"',
 '1490400000000,, "#ffffff"',
 '1490486400000,, "#ffffff"',
 '1490572800000,, "#ffffff"',
 '1490659200000,, "#ffffff"',
 '1490745600000,, "#ffffff"',
 '1490832000000,, "#ffffff"',
 '1490918400000,, "#ffffff"',
 '1491004800000,, "#ffffff"',
 '1491091200000,, "#ffffff"',
 '1491177600000,, "#ffffff"']

它将提供如下文件

BasicDBObject query = new BasicDBObject();
BasicDBObject selectGenderOnly = new BasicDBObject();
selectGenderOnly.put("gender", 1);

DBCursor cursor = dbcollection.find(query, selectGenderOnly); // db.collection.find({}, {"gender": 1}) & _id field included by default in result set

 while (cursor.hasNext()) {
    BasicDBObject obj = (BasicDBObject) cursor.next();
    // use obj
    // ...
  }