0

I'm trying to follow this post to create a "contains" query in Java. The problem is it's giving me an error.

At the moment i have the following code:

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

The error it gives me is in the 'query' line:

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

I use the cursor for inserting it into a JTable.
Driver: mongo-java-driver-3.4.2
Thanks in advance.

Community
  • 1
  • 1
qapt
  • 101
  • 2
  • 12

1 Answers1

2

Use new Document and MongoCollection api's for java driver 3.x version.

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

For accesssing MongoCursor,

FindIterable<Document> results  = coll.find(Filters.regex("title", "name"));
MongoCursor<Document> cursor = results.iterator();
s7vr
  • 73,656
  • 11
  • 106
  • 127