MongoDB通过Java驱动程序获取集合

MongoDB通过Java驱动程序获取集合

本文介绍了MongoDB通过Java驱动程序获取集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到以下错误:

I am getting the following error:

程序无法获取集合属性.

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

推荐答案

尝试一下:

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

由于3.0系列Java驱动程序中与数据库,集合等相关的更改很多,请通过快速浏览更多的了解.

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

这篇关于MongoDB通过Java驱动程序获取集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 03:19