【问题标题】:With the mongodb-java-api, is it possible to "select" the objectID and return the value from a Mongodb.find operation in one operation?使用 mongodb-java-api,是否可以在一次操作中“选择”objectID 并从 Mongodb.find 操作中返回值?
【发布时间】:2015-05-02 02:27:07
【问题描述】:

我有兴趣从单个文档中查找 id 作为查找操作的结果。

在 Robomongo 中,我可以通过以下语句获得有问题的值:

db.collection.find({ "field" : {$exists: true}}).limit(1).next()._id.valueOf()

我必须使用最少的 Java 代码来获得相同的代码?

【问题讨论】:

    标签: mongodb mongodb-query mongodb-java


    【解决方案1】:

    因为你只需要找到一个你可以使用的文档

    DBCollection.findOnefindOne(DBObject query, DBObject projection)
    

    另外,您只需找到_id。所以,我只预测_id

        MongoClient mongo = new MongoClient("localhost", 27017);
        DB db = mongo.getDB("test");
        DBCollection collection = db.getCollection("collection");
        DBObject obj =  collection.findOne(new BasicDBObject("name", new BasicDBObject(
                "$exists", true)),new BasicDBObject("_id",1));
        ObjectId id = (ObjectId) obj.get("_id");        
        System.out.println(id.toHexString());
    

    【讨论】:

      猜你喜欢
      • 2016-01-11
      • 1970-01-01
      • 1970-01-01
      • 2010-12-31
      • 1970-01-01
      • 1970-01-01
      • 2021-07-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多