MongoDB Aggregration Framework and Java Driver making $or condtion work

允我心安 提交于 2019-12-11 14:19:39

问题


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!


回答1:


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);



回答2:


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);


来源:https://stackoverflow.com/questions/18732557/mongodb-aggregration-framework-and-java-driver-making-or-condtion-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!