Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb fetch collections by java driver

Tags:

java

mongodb

I am getting the following error: enter image description here

Program can't fetch collections attributes.

        MongoClient mongoClient = new MongoClient(new ServerAddress("localhost", 27017));

        MongoDatabase db = mongoClient.getDatabase("local");

        MongoCollection collection = db.getCollection("sadi");

        BasicDBObject searchQuery = new BasicDBObject();
        searchQuery.put("name","amran");
        DBCursor cursor = collection.find(searchQuery);
like image 631
smamran Avatar asked Jul 29 '26 17:07

smamran


1 Answers

try this:

    import org.bson.Document;

    import com.mongodb.BasicDBObject;
    import com.mongodb.MongoClient;
    import com.mongodb.ServerAddress;
    import com.mongodb.client.MongoCollection;
    import com.mongodb.client.MongoCursor;
    import com.mongodb.client.MongoDatabase;

    MongoClient mongoClient = new MongoClient(new ServerAddress("localhost", 27017));

    MongoDatabase db = mongoClient.getDatabase("local");

    MongoCollection<Document> collection = db.getCollection("sadi");

    BasicDBObject searchQuery = new BasicDBObject();
    searchQuery.put("name","amran");

    MongoCursor<Document> cursor = collection.find(searchQuery).iterator();  
    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next().toJson());
        }
    } finally {
        cursor.close();
    }

As there are many changes in 3.0 series java driver related to database, collection,etc. Please go through quick tour for more understanding.

like image 119
Dev Avatar answered Aug 01 '26 06:08

Dev