查找 Java Mongodb 集合中的所有对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29659504/
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-11 08:23:31  来源:igfitidea点击:

Find all objects in collection Java Mongodb

javamongodb

提问by blue-sky

Below code finds the first document in a collection :

下面的代码查找集合中的第一个文档:

package database;

import com.mongodb.BasicDBObject;
import com.mongodb.BulkWriteOperation;
import com.mongodb.BulkWriteResult;
import com.mongodb.Cursor;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.ParallelScanOptions;
import com.mongodb.ServerAddress;

import java.net.UnknownHostException;
import java.util.List;
import java.util.Set;

import static java.util.concurrent.TimeUnit.SECONDS;

// based on http://mongodb.github.io/mongo-java-driver/2.13/getting-started/quick-tour/

public class Mongo {

    public void getCon() {
        // or
        MongoClient mongoClient;
        try {
            mongoClient = new MongoClient("localhost", 27017);
            DB db = mongoClient.getDB("mydb");
            DBCollection coll = db.getCollection("testCollection");

            BasicDBObject doc = new BasicDBObject("name", "MongoDB")
                    .append("type", "database")
                    .append("count", 1)
                    .append("info",
                            new BasicDBObject("x", 203).append("y", 102));
            coll.insert(doc);

            coll.findOne();
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}

There does not appear to be a findAll method. How to find all the documents in the collection testCollection?

似乎没有 findAll 方法。如何查找集合中的所有文档testCollection

采纳答案by Konstantin Yovkov

You have to use the DBCollection.find()method, which

您必须使用该DBCollection.find()方法,其中

Select all documents in collection and get a cursor to the selected documents.

选择集合中的所有文档并将光标移至所选文档。

So, what you have to do, is:

所以,你必须做的是:

DBCursor cursor = coll.find();
while (cursor.hasNext()) {
   DBObject obj = cursor.next();
   //do your thing
}

回答by jyemin

If you know that the query will return a small enough number of documents, you can use the DBCursor.toArray() method to get all the results into a List:

如果您知道查询将返回足够少的文档,您可以使用 DBCursor.toArray() 方法将所有结果放入一个列表中:

List<DBObject> all = coll.find().toArray();