简体   繁体   English

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

[英]How can I get the multiple attributes according to unique ids in MongoDB?

I'd like to retrieve say a list of only ids and genders as list<DBObject> from 我想从中检索说只有ID和性别的list<DBObject>作为list<DBObject>

{ "_id": 123 , "gender": m, "occupation": athlete },
{ "_id": 456 , "gender": f, "occupation": basketball },
...

Tried using the following but did not work. 尝试使用以下方法,但无效。 With query being initiated as a new BDObject gender : 1 将查询作为新的BDObject性别启动:1

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

"_id" is unique, so no need to call distinct function on it “ _id”是唯一的,因此无需在其上调用不同的函数

If you want to get all the documents with gender and _id you can achieve it in following way 如果要获取所有带有性别和_id的文档,则可以通过以下方式实现

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
    // ...
  }

It will provide the documents like below 它将提供如下文件

{"_id":123 , "gender": m}
{"_id":456 , "gender": f}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM