java - 使用 Java 和 MongoDB 创建 'contains' 查询

标签 java mongodb mongodb-java

我正在尝试遵循此post在 Java 中创建“包含”查询。问题是它给了我一个错误。

目前我有以下代码:

MongoClient mongoClient = null;
DBCursor cursor = null;

mongoClient = new MongoClient( "localhost" , 27017 );
DB db = mongoClient.getDB("bd-films");
DBCollection coll = db.getCollection("films");

DBObject query = new BasicDBObject({"title" : {$regex : "name"}});         
cursor = coll.find(query);

它给我的错误是在“查询”行中:

Syntax error on token ""title"", invalid Label
Syntax error, insert ";" to complete Statement
Syntax error on token ")", delete this token

我使用游标将其插入到 JTable 中。
驱动程序:mongo-java-driver-3.4.2
提前致谢。

最佳答案

对 Java 驱动程序 3.x 版本使用新的 DocumentMongoCollection api。

 MongoClient mongoClient = new MongoClient("localhost", 27017);
 MongoDatabase db = mongoClient.getDatabase("bd-films");
 MongoCollection<Document> coll = db.getCollection("films");
 List<Document> results  = coll.find(Filters.regex("title", "name")).into(new ArrayList<>())

用于访问MongoCursor

FindIterable<Document> results  = coll.find(Filters.regex("title", "name"));
MongoCursor<Document> cursor = results.iterator();

关于java - 使用 Java 和 MongoDB 创建 'contains' 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42678991/

相关文章:

java - JBoss 中的 ModuleNotFoundException 错误

java - JTextArea .setText/.append 不起作用

mongodb - 如何获取MongoDB Realm App的服务?

mongodb - 特定字段作为 mongodb 的结果

使用 Java 对所有字段进行 MongoDB 文本索引

java - 如何使用distinct/aggregate获取匹配多个查询的所有字段

java - 我如何将用户从 GUI 给出的输入存储到字符串数组以供将来在 java 中使用

java - 在 HTML 中使用 Java applet 方法

javascript - 将语言 (ISO 639) 存储为数字

mongodb - 如何在mongodb中将字符串转换为数值