2016-07-31 55 views
0

我有一个字符串与聚合json查询(从文件加载)为mongodb。在robomongo中,它运行良好。因此,在robomongo,我有:如何在字符串中使用json执行聚合mongo查询?

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

JSON文件是一样的,但与第一和去除,使得它的JSON的最后一行。当我用Java加载它时,它解析正确。解析的结果恰好是一个“BasicDBList”:

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

现在,我想这传递给聚合函数,但它不工作:

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

这条线给出:

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

有没有办法转换类型?我应该用另一种方式来做吗?

回答

0

你是不远处的解决方案:

的聚合函数有:.aggregate(List<DBObject>) 但是你要使用的JSON.parse让你强制转换成它,如果你在你的查询列表,因此没问题

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

结果可以重复。