how to query mongodb using the $ne operator? - java

i'm trying to do a $ne query in mongodb while using a regex, but it doesn't seem to work. the $ne (not equal) operator works fine when i don't use a regex though.
BasicDBObject q = new BasicDBObject()
q.put(field, ["\$ne": value])
the above works fine, the result set doesn't contain any documents that has that value for that field.
but i need it to be case insensitive. so i did this
q.put(field, ["\$ne": Pattern.compile(value, Pattern.CASE_INSENSITIVE)])
but this doesn't work..
so i thought, let me go to the command line and see if i can do it manually. so i did this:
db.Order.find({"bill.recipient.name": {$ne: /diep/i}},{"bill.recipient.name":1})
and it still doesn't work!
any ideas?

Try using $not instead of $ne.
http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-Metaoperator%3A%24not

You can construct your query this way also
BasicDBObject query = new BasicDBObject();
query.append(fieldname,new BasicDBObject("$ne", value));

Related

JPA CriteriaBuilder value like column

I'm trying to create a query using CriteriaBuilder where I need to have a predicate where the value of the predicate is like the value in the database.
Basically, I need to be able to do the following:
WHERE myTestValue LIKE columnValue
In native queries, it is an option to do that, but using the CriteriaBuilder or NamedQueries, it does not seem to work.
String myValue = "foo#bar.com";
cb.where(cb.like(myValue, root.get(Entity_.email));
Is there an option in JPA to do it like this? Or should I fall back to native queries?
EDIT
I need to be able to check if a given value matches a wildcard entry in database. So the database has a record %#bar.com%, and I need to check if my given value foo#bar.com matches to that record.
I think your params should be other way round:
cb.where(cb.like(root.get(Entity_.email),myValue);
Aditionally you may need to use add this to the second param:
cb.where(cb.like(root.get(Entity_.email),"%"+myValue+"%");
Chris found the answer. First I need to "generate" a parameter.
ParameterExpression<String> senderEmailParameter = cb.parameter(String.class, "senderEmailParameter");
Path<String> senderEmailPath = root.get(Entity_.senderEmail);
Predicate predEmail = cb.like(senderEmailParameter, senderEmailPath);
And then I need to fill the parameter in the query.
q.where(predEmail);
return em.createQuery(q).setParameter("senderEmailParameter", senderEmail).getSingleResult();
This works! Thanks Chris!

Using regular Expressions with Mongodb

I am using Java Spring to work with Mongodb. I need to find documents which the word 'manager' is existed in description field. I tried following two method
Method 1
Query query = new Query();
query.addCriteria(Criteria.where("discription").regex("/\bmanager\b/"));
Method 2
Query query = new Query();
Pattern p = Pattern.compile("/\bmanager\b/");
query.addCriteria(Criteria.where("discription").regex(p));
But none of these were worked. I tried it with mongodb console like this
db.test.find({discription: {$regex: /\bmanager\b/}})
It worked as I expected. What's wrong with my Java code.
You don't have to add the slashes in the regex expression, as the regex method takes care of it. So
Query query = new Query();
query.addCriteria(Criteria.where("description").regex("\bmanager\b"));
should work.
It looks like you can just pass your regex string straight through without using Pattern.compile(). Have you tried that?

Morphia query with or operator

I want to know how to write a Morphia mongodb query with 'or' operator
I wrote mongodb query like this and this work fine
db.Inv.find({$or:[{sug_id:2},{grp_id:2}]})
But i got confused when i try to write this in morphia, following query is wrong but how can write something similar to this
List<Inv> invs = ds.find(Inv.class).field("grp_id").hasAnyOf(grpId).or(field("sug_id")).hasAnyOf(grpId).asList();
Thanks
not sure why hasAnyOf() is in there but try this:
Query<Inv> query = ds.find(Inv.class);
query.or(
query.criteria("grp_id").equal(2),
query.criteria("sug_id").equal(2));
List<Inv> invs = query.asList();

How to query mongodb with “like” using the java api without using Pattern Matching?

Currently I am using java to connect to MONGODB,
I want to write this sql query in mongodb using java driver:
select * from tableA where name like("%ab%")
is their any solution to perform the same task through java,
the query in mongodb is very simple i know, the query is
db.collection.find({name:/ab/})
but how to perform same task in java
Current I am using pattern matching to perform the task and code is
DBObject A = QueryBuilder.start("name").is(Pattern.compile("ab",
Pattern.CASE_INSENSITIVE)).get();
but it makes query very slow I think , does a solution exist that does not use pattern matching?
Can use Regular Expressions. Take a look at the following:
http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-RegularExpressions
Make sure you understand the potential performance impacts!
DBObject A = QueryBuilder.start("name").is(Pattern.compile("ab",
Pattern.CASE_INSENSITIVE)).get();
I think this is one of the possible solution, you need to create index to achieve those.
Why do you fear the regular expressions? Once the expression is compiled they are very fast, and if the expression is "ab" the result is similar to a function that search a substring in a string.
However to do what you need you have 2 possibilities:
The first one, using regular expression, as you mention in your question. And I believe this is the best solution.
The second one, using the $where queries.
With $where queries you can specify expression like these
db.foo.find({"$where" : "this.x + this.y == 10"})
db.foo.find({"$where" : "function() { return this.x + this.y == 10; }"})
and so you can use the JavaScript .indexOf() on string fields.
Code snippet using the $regex clause (as mentioned by mikeycgto)
String searchString = "ab";
DBCollection coll = db.getCollection("yourCollection");
query.put("name",
new BasicDBObject("$regex", String.format(".*((?i)%s).*", searchString)) );
DBCursor cur = coll.find(query);
while (cur.hasNext()) {
DBObject dbObj = cur.next();
// your code to read the DBObject ..
}
As long as you are not opening and closing the connection per method call, the query should be fast.

How to specify UUID in mongo $where clause

I have an object that was stored via mongo-java-driver. Object uses java.util.UUID for its _id field. Following is presentation of object via mongo shell:
> db.b.find()
{ "_id" : BinData(3,"zUOYY2AE8WZqigtb/Tqztw==") }
I have a requirement to process searching via $where clause. I use following code to do it:
Mongo m = new Mongo();
DBCollection coll = m.getDB("a").getCollection("b");
coll.save(new BasicDBObject("_id", UUID.randomUUID()));
// ??? - don't know what should be specified
DBObject query = new BasicDBObject("$where", "this[\"_id\"] == " + ???);
coll.find(query).count()
The question is what should I specify instead of ??? to make it work?
Thanks for any help.
My invesigation shown that only one way to do it is rewriting a query in object based way (I mean migration of $where clause part to BasicDBObject based query). In such case mongo-java-driver supports java.util.UUID without any additional effort.

Categories

Resources