查询MongoDB字段

时间:2015-06-09 06:02:42

标签: java mongodb

我正在使用java 3.0 driver的MongoDB。在手册中,我只找到了find()findOne(),它会向我提供所有文档。 我有一个场景,我应该通过查询得到_id值。例如,在SQL中从表名中选择_id

{
        "_id" : ObjectId("557660c074cd60207e337aed"),
        "contactMethodId" : [
                {
                        "contactMethodId" : "contactMethodId",
                        "contactMethodUsageTypeCode" : null,
                        "contactMethodTypeCode" : "contactMethodTypeCode",
                        "contactMethodValue" : "contactMethodValue",
                        "contactContentTypeCode" : "contactContentTypeCode",
                        "contactContentMaxSize" : "contactContentMaxSize",
                        "comment" : "comment",
                        "preferredInt" : "preferredInd",
                        "effectiveStartDateOfContact" : "effectiveStartDateOfContact",
                        "effectiveEndDateOfContact" : "effectiveEndDateOfContact",
                        "standardizedIndOfContact" : "standardizedIndOfContact",
                        "lastVerifiedDateOfContact" : "lastVerifiedDateOfContact"
                }
        ]
}

_id默认生成。

我想要从表名中选择_id,我应该在java中获得ObjectId("557660c074cd60207e337aed")。任何建议。

3 个答案:

答案 0 :(得分:0)

您可以使用以下内容:

BasicDBObject projection = new BasicDBObject();
projection.put("_id",1);
DBCursor cursor = collection.find(new BasicDBObject(),projection);

然后使用光标上的循环读取。

while (cursor.hasNext()) {
    System.out.println("Result : -"+cursor.next());
}

答案 1 :(得分:0)

检查此代码,使用mongo版本3.0.3和Mongo Java驱动程序版本3.0.1进行测试

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;
public class demo {
  public static void main(String[] args) throws Exception {
    Mongo mongo = new Mongo("localhost", 27017); // set host and port of mongo 
    DB db = mongo.getDB("demo"); // set DB name
    DBCollection collection = db.getCollection("collectionName"); // set collection Name
    BasicDBObject query = new BasicDBObject();
    BasicDBObject project = new BasicDBObject();
    project.put("_id", 1); // set project to get _id 
    DBCursor cursorDoc = collection.find(query, project); // find query with projection
    while(cursorDoc.hasNext()) {
      BasicDBObject object = (BasicDBObject) cursorDoc.next();
      String _id = object.get("_id").toString(); // If required convert the _id to String
      System.out.println(object); // print _id with object 
      System.out.println(_id); // print _id as a String
    }
  }
}

答案 2 :(得分:0)

MongoIterable<Document> = mongoClient.getDatabase("foo")
   .getCollection("bob")
   .find()
   .projection(new Document("_id", 1))