我正在尝试遵循此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 版本使用新的 Document
和 MongoCollection
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/