gpt4 book ai didi

java - Mongodb 通过 Java 驱动程序获取集合

转载 作者:可可西里 更新时间:2023-11-01 09:56:49 25 4
gpt4 key购买 nike

我收到以下错误: enter image description here

程序无法获取集合属性。

        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驱动在数据库、集合等方面有很多变化。请通过quick tour为了更多的理解。

关于java - Mongodb 通过 Java 驱动程序获取集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31108943/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com