blue-sky
blue-sky

Reputation: 53806

Find all objects in collection Java Mongodb

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 ?

Upvotes: 5

Views: 34788

Answers (3)

Vladi
Vladi

Reputation: 1990

My solution :

preparation :

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

declare of cursor

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

Upvotes: 0

jyemin
jyemin

Reputation: 3813

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:

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

Upvotes: 6

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62864

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

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
}

Upvotes: 10

Related Questions