2017-03-08 45 views
0

我试图按照这个post在Java中创建“包含”查询。问题是它给我一个错误。使用Java和MongoDB创建'包含'查询

此刻,我有以下代码:

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
在此先感谢。

+1

也许您的查询应该是这样的...... 'DBOBJECT查询=新BasicDBObject( “称号”,新BasicDBObject( “$正则表达式”,“名称“));' –

+0

解决了我的问题,谢谢 –

回答

1

使用新的DocumentMongoCollection api's for java驱动3.x版本。

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

对于accesssing MongoCursor

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