user2661044
user2661044

Reputation: 21

Complex query in Morphia

in my method Java, I would like to pass as a parameter to my collection MongoDB a complex query like this one:

{"$or": [{"$and": [{"contextID": "AKKA"}, {"messageID": "PIPPO"}]},
         {"$and": [{"domain": "Niguarda"}, {"hostName": {"$ne": "hostServer"}}]}
        ]
}

The string that contains the query is variable and passed as parameter in query string.

I tried to pass the query as parameter to method criteria

(queryDB.criteria("
    {"$or": [
        {"$and": [{"contextID": "AKKA"}, {"messageID": "PIPPO"}]},
        {"$and": [{"domain": "Niguarda"}, {"hostName": {"$ne": "hostServer"}}]}]
    }"
) 

but it does not work.

Any suggestions?

Upvotes: 1

Views: 2647

Answers (2)

user2661044
user2661044

Reputation: 21

This is now the code (it's works fine but I abandoned morphia):

public long count(String query) throws Exception {
    DB db = mongoClient.getDB(mongoDBName);
    DBCollection dbCollection = db.getCollection(mongoDBCollection);

    DBObject dbObjQuery;

    long l = 0;
    try {

        if (!(query == null)) {
            dbObjQuery = (DBObject) JSON.parse(query);
            l = dbCollection.find(dbObjQuery).count();
        } else {
            l = dbCollection.find().count();
        }


    } catch (Exception e) {

    } finally {

    }

    return l;

}

There is another way to do this with morphia?

Upvotes: 1

Joe Minichino
Joe Minichino

Reputation: 2773

What you're trying to do would be

Query q = dao.createQuery();
q.or(
 q.and(new Criteria[]{ dao.createQuery().filter("contextID").equal("AKKA"),
                       dao.createQuery().filter("messageID").equal("PIPPO") }),
 q.and(new Criteria[]{ dao.createQuery().filter("domain").equal("Niguarda"),
                       dao.createQuery().filter("hostname").notEqual("hostServer") })
);

Upvotes: 1

Related Questions