1

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.

8
  • please format properly Commented Dec 28, 2017 at 2:24
  • Not able to understand your question. Please edit it to make it more readable. Commented Dec 28, 2017 at 2:28
  • 1
    You're ending the object in the middle. Replace all the },{ with ,. Voting to close as typo. Commented Dec 28, 2017 at 2:49
  • 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.' Commented Dec 28, 2017 at 3:11
  • The error 16435 has an answer here: stackoverflow.com/questions/39060221/… Commented Dec 28, 2017 at 3:42

1 Answer 1

0

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:

Sign up to request clarification or add additional context in comments.

1 Comment

Thank your answer. But, this example can not resolve my issue. I need to convert all parts in java String to mongo DBObject.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.