0

I have a string with an aggregate json query (loaded from a file) for mongodb. In robomongo, it works well. So in robomongo, I have:

db.getCollection('Odds').aggregate(
[
{
     "$lookup": {
        "from": "...",
        "localField": "...",
        "foreignField": "...",
        "as": "..."
     }
},
{    "$unwind": "$..." },
{
     "$redact": {
         ... etc ...
     }
}
]
)

The json file is just the same but with the first and the last line removed so that it's json. When I load this in Java, it parses correctly. The result of the parse happens to be a "BasicDBList":

String query = "..."; // read from file
BasicDBList q = (BasicDBList) JSON.parse(query);

Now, I'm trying to pass this to the aggregate function, but it doesn't work:

new MongoClient().getDatabase("db").getCollection("coll").aggregate(q);

That line gives:

The method aggregate(List<? extends Bson>) in the type MongoCollection<Document> is not applicable for the arguments (BasicDBList)

Is there a way to convert the types? Should I do it in another way?

1 Answer 1

1

You are not far from the solution:

The aggregate function takes: .aggregate(List<DBObject>) But the JSON.parse you want to use lets you typecast into it, if you have a list in your query, so no Problem

String query="[....}";
List<DBObject> q= (List<DBObject>)JSON.parse(query);
Iterable<DBObject> result=new MongoClient().getDatabase("db").getCollection("coll").aggregate(q).results();`

The results can than be iterated.

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

Comments

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.