Question

I am working on a method that queries a mongoDB using the aggregator framework. I have built up the aggregate but I keep getting the following exception:

Pipeline::run(): unrecognized pipeline op \"$or"

If I understand correctly when you append or add DBObjects to the query they are implicitly added as and operations. I may be really tired right now but I can't think of a way to or two conditions with the aggregation framework.

The following is a snippet of my code:

    DBObject matchCriteriaTransmitter = new BasicDBObject("$match",
            new BasicDBObject("someKey": "someValue").
                    append("someKey": "someValue"));

    DBObject matchCriteriaReceiver = new BasicDBObject("$match",
            new BasicDBObject("someKey": "someValue").
                    append("someKey": "someValue"));

    BasicDBList or = new BasicDBList();
    or.add(matchCriteriaTransmitter);
    or.add(matchCriteriaReceiver);

    DBObject matchCriteria = new BasicDBObject("$or", or);

    DBObject sortCriteria = new BasicDBObject("$sort",
            new BasicDBObject("compoundIndex.scenarioDtg", -1));

    DBObject limitCriteria = new BasicDBObject("$limit", 1);


    DBCollection collection = dao.getCollection();

    AggregationOutput output = collection.aggregate(matchCriteria, sortCriteria, limitCriteria);

Any insight is greatly appreciated!

Was it helpful?

Solution

Check the docs you likely to use $or as a pipeline operator but there is no such operator: DOC

INstead you can construct an $match operator which is inside can contain an or clause

Something like this in shell:

db.collection.aggregate({$match:{$or:[{someKey:'someValue'},{someOtherKey:'someOtherValue'}]}})

What you have to change is something like this in JAVA:

Change this:

DBObject matchCriteria = new BasicDBObject("$or", or);

To this:

DBObject orCriteria = new BasicDBObject("$or", or);
DBObject matchCriteria = new BasicDBObject("$match", orCriteria);

OTHER TIPS

I have done this in javascript. I did wrap the $or object with a $match object. I wonder if you need to do something similar:

DBObject matchCriteriaTransmitter = new BasicDBObject("someKey": "someValue")
                                        .append("someKey": "someValue");

DBObject matchCriteriaReceiver = new BasicDBObject("someKey": "someValue")
                                     .append("someKey": "someValue");

BasicDBList or = new BasicDBList();
or.add(matchCriteriaTransmitter);
or.add(matchCriteriaReceiver);

DBObject matchCriteria = new BasicDBObject("$match", or);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top