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.

2
  • 1
    Maybe your query should look like this... DBObject query = new BasicDBObject("title", new BasicDBObject("$regex", "name")); Commented Mar 8, 2017 at 18:27
  • Solved my problem, thanks Commented Mar 8, 2017 at 18:34

1 Answer 1

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.