gpt4 book ai didi

java - 如何在 Java 中运行动态 mongo 查询

转载 作者:行者123 更新时间:2023-12-02 01:41:01 25 4
gpt4 key购买 nike

我正在尝试在 Java 应用程序中运行动态 mongodb 查询。但我收到 NoClassDefFound 错误。我做错了什么?

DB mongoDB = mongoclient.getDB("test");

String query = "db.test.find({'address':'Sydney'})";
MongoQuery mongoQuery = new MongoQueryParser().parse(query, new
HashMap());

BasicDBList results = mongoQuery.execute(mongoDB);
System.out.println(results.size());

我除了结果是:

{ "_id" : "106", "full_name" : "Susan Dixit", "address" : "Sydney" }

但我收到以下错误:

Exception in thread "main" java.lang.NoClassDefFoundError: 
com.mongodb.casbah.MongoDB
at com.ee.dynamicmongoquery.MongoQuery.execute(MongoQuery.scala:13)
at mongodata.main(mongodata.java:29)
Caused by: java.lang.ClassNotFoundException: com.mongodb.casbah.MongoDB.

最佳答案

您可以尝试使用 db.eval 命令。例如:

MongoDatabase database = mongoClient.getDatabase("test");

Bson command = new Document("eval", "db.test.find({\"address\":\"Sydney\"})");
Document result = database.runCommand(command);

或者,您也可以仅将过滤器作为字符串传递,以防您想要动态提供。示例:

DBCollection collection = database.getCollection("test");

BasicDBObject query = BasicDBObject.parse("{\"address\":\"Sydney\"}");

FindIterable<Document> dumps = collection.find(query);

关于java - 如何在 Java 中运行动态 mongo 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57488543/

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