Reputation: 1
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?
Upvotes: 0
Views: 2429
Reputation: 118
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.
Upvotes: 1