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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20357906/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 01:19:51  来源:igfitidea点击:

How to run find query with a selected field using Java driver

javamongodb

提问by Watt

I am trying to run following query using mongo java driver

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

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

I need all the ids from the collection. The above query runs fine in mongo client.

我需要集合中的所有 ID。上述查询在 mongo 客户端中运行良好。

But, I need results through my java code. I tried below non-workingcode.. because, as you can see below I am unable to create {},{_id:1}for find()method from the java driver.

但是,我需要通过我的 Java 代码获得结果。我尝试以下非工作代码..因为,正如你可以看到下面我无法创建 {},{_id:1}用于find()从Java驱动程序的方法。

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();
}

Please advise the appropriate way to initialize queryobject

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

Edit:

编辑:

I can always get the ids by following:

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

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

But, still it would be nicer to learn how to create the accurate query object, maybe that would be faster on big (+30gb) dataset as mine. So, I am keeping this question open.

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

采纳答案by JohnnyHK

Keep your query conditions and selected fields objects as separate parameters to find:

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

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

回答by Arun Kumar Giri

You can project fields from a collection as shown below.

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

// 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);

回答by shiv

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"}