如何使用Java驱动程序运行查找所选字段的查询

时间:2013-12-03 17:35:38

标签: java mongodb

我正在尝试使用mongo java驱动程序运行以下查询

db.myCollection.find({},{_id:1})

我需要收藏中的所有ID。 上面的查询在mongo客户端中运行良好。

但是,我需要通过我的java代码获得结果。 我在非工作代码下面尝试过..因为,正如您在下面看到的,我无法创建   来自java驱动程序的{},{_id:1}方法的find()

BasicDBObject query= new BasicDBObject("","").append("",new BasicDBObject("_id","1"));

DBCursor cursor = coll.find(query);


try {
    while(cursor.hasNext()) {
        System.out.println(cursor.next());
    }
} finally {
    cursor.close();
}

请告知初始化query对象的适当方式

修改

我总是可以通过以下方式获取ID:

DBCursor cursor = coll.find();
        try {
            while(cursor.hasNext()) {
                System.out.println(cursor.next().get("_id"));
            }
        } finally {
            cursor.close();
        }

但是,学习如何创建准确的查询对象仍然会更好,也许在我的大(+ 30gb)数据集上会更快。所以,我打开这个问题。

3 个答案:

答案 0 :(得分:3)

将查询条件和选定的字段对象作为单独的参数保存到find

BasicDBObject query = new BasicDBObject();
BasicDBObject fields = new BasicDBObject("_id", "1");
DBCursor cursor = coll.find(query, fields);

答案 1 :(得分:1)

Below snippet gets all documents where “firstName” is “Gopi”.
<pre>
BasicDBObject query = new BasicDBObject();
query.put("firstName", "Gopi");

DBCursor cursor = collection.find(query);

import java.net.UnknownHostException;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
import com.mongodb.DB;
import com.mongodb.DBCollection;

public class FindDocument {

    /* Step 1 : get mongoClient */
    public static MongoClient getMongoClient(){
        MongoClient mongoClient = null;
         try {
             mongoClient = new MongoClient( "localhost" , 27017 );
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
         return mongoClient;
    }

    public static void main(String args[]){
        MongoClient mongoClient = getMongoClient();

        /* Step 2: Connect to DB */
        DB db = mongoClient.getDB("sample");

        /*Step 3 : Get collection */
        DBCollection collection = db.getCollection("employee");

        /* Step 4 : Create Query object */
        BasicDBObject query = new BasicDBObject();
        query.put("firstName", "Gopi");

        /* Step 5 : Get all documents */
        DBCursor cursor = collection.find(query);

        /* Step 6 : Print all documents */
        while(cursor.hasNext()){
            System.out.println(cursor.next());
        }
    }

}

</pre>



Output

{ "_id" : 3.0 , "firstName" : "Gopi" , "lastName" : "Battu"}

答案 2 :(得分:0)

您可以从集合中投影字段,如下所示。

// Create query and fields
BasicDBObject query = new BasicDBObject();
BasicDBObject fields = new BasicDBObject();

// Assign 1 or 0 for projecting a specific field.
fields.put("_id", 0);
fields.put("Student ID", 1);
fields.put("Student Age", 1);
fields.put("Gender", 1);

// Pass query and fields to find()
DBCursor cursor = dbCollection.find(query, fields);