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

时间:2015-04-15 19:48:04

标签: java mongodb

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

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

    }
}

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

3 个答案:

答案 0 :(得分:9)

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

  

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

所以,你要做的是:

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

答案 1 :(得分:6)

如果您知道查询将返回足够少的文档,则可以使用DBCursor.toArray()方法将所有结果导入List:

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

答案 2 :(得分:0)

我的解决方案:

准备:

       MongoClient mongoClient = new MongoClient("localhost", 27017);
       MongoDatabase database = mongoClient.getDB("mydb");
       MongoCollection<Document> collection = database.getCollection("collectionName");

声明游标

       MongoCursor<Document> cursor = collection.find().iterator();
        while (cursor.hasNext()) {
            System.out.println("collection is " +cursor.next() );
        }