MongoDB : $not implementation in java

42 views
Skip to first unread message

satyam chandel

unread,
Jul 25, 2016, 7:21:24 AM7/25/16
to mongodb-user
Hi Everyone,

I am trying to implement following query from java code:

{ "Post Text" : { "$not" : /.*golf.*/i}}

BasicDBObject not = new BasicDBObject();
not.append("$not", "/.*golf.*/i");

BasicDBObject query = new BasicDBObject();
query.add("Post Text", not);

When I am running above query, getting this log:

Cursor id=0, ns=journaldev.Rotunda, query={ "Post Text" : { "$not" : { "$regex" : "/.*golf.*/i"}}}, numIterated=0, readPreference=primary

extra quotes around the regular expression are creating problem. Can someone help me out in this?


Thanks for any suggestion!!!!

Wan Bachtiar

unread,
Aug 1, 2016, 2:16:02 AM8/1/16
to mongodb-user

extra quotes around the regular expression are creating problem. Can someone help me out in this?

Hi Satyam,

To use the $not operator in combination with the $regex operator via a driver interface, you would have to utilise the language’s regex capability to create a regex object. For example, in Java you can use java.util.regex.Pattern.

import java.util.regex.Pattern;
import static com.mongodb.client.model.Filters.not;
import static com.mongodb.client.model.Filters.regex;

Pattern re_pattern = Pattern.compile(".*golf.*", Pattern.CASE_INSENSITIVE);
MongoCursor<Document> cursor = collection.find(not(regex("PostText", re_pattern)));

The snippet above was tested using MongoDB v3.2.8 and mongo-java-driver v3.3

Best regards,

Wan.

Reply all
Reply to author
Forward
0 new messages