1
votes

I want to parse a java string to mongo DBObject or BasicDBObject as below.

List<DBObject> query = new ArrayList<DBObject>();

String allQry = "{ \"$match\" : { \"CUSTOMERID\" : { \"$gt\" : 10}}}, { \"$project\" : { \"CUSTOMERNAME\" : 1 , \"COUNTRY\" : 1 , \"CUSTOMERID\" : 1}},{ \"$sort\" : { \"COUNTRY\" : 1}}";

BasicDBObject dbobj = BasicDBObject.parse(allQry);

query.add(dbobj);

System.out.println("qqqquery : "+query);

Cursor aggCur = collection.aggregate(query, aggOpt);

After run above example codes, it outputs qqqquery : [{ "$match" : { "CUSTOMERID" : { "$gt" : 10}}}]. There are $match , $project and $sort in allQry. Why do not it includes $project and $sort in this query? It only includes $match, who can help to check this reason? Thanks.

1
please format properly - Sreehari R
Not able to understand your question. Please edit it to make it more readable. - aakash
You're ending the object in the middle. Replace all the },{ with ,. Voting to close as typo. - shmosel
Thank your help to edit example code. I replace all },{ with , it will throw excepton com.mongodb.MongoCommandException: Command failed with error 16435: 'A pipeline stage specification object must contain exactly one field.' - Marika
The error 16435 has an answer here: stackoverflow.com/questions/39060221/… - tkruse

1 Answers

0
votes

Following this tutorial: http://pingax.com/trick-convert-mongo-shell-query-equivalent-java-objects/

you could add all parts of your query like this:

MongoClient mongo = new MongoClient();
DB db = mongo.getDB("pingax");

DBCollection coll = db.getCollection("aggregationExample");

/*
 MONGO SHELL : db.aggregationExample.aggregate(
 {$match : {type : "local"}} ,
 {$project : { department : 1 , amount : 1 }}
 );
 */
 DBObject match = new BasicDBObject("$match", new BasicDBObject("type", "local")); 

 DBObject project = new BasicDBObject("$project", new BasicDBObject("department", 1).append("amount", 1));

 AggregationOutput output = coll.aggregate(match,project,group,sort);

Related: