如何在字符串中使用json执行聚合mongo查询? [英] How to perform an aggregate mongo-query using json in a String?

查看:253
本文介绍了如何在字符串中使用json执行聚合mongo查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用于mongodb的带有汇总json查询(从文件加载)的字符串.在robomongo中,它运作良好.所以在robomongo中,我有:

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 ...
     }
}
]
)

json文件是一样的,只是删除了第一行和最后一行,所以它是json.当我在Java中加载它时,它可以正确解析.解析的结果恰好是"BasicDBList":

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);

该行给出:

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?

推荐答案

您距离解决方案不远:

聚合函数采用:.aggregate(List<DBObject>) 但是,如果您的查询中有列表,则要使用的JSON.parse可以让您进行类型转换,因此没有问题

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();`

然后可以迭代结果.

这篇关于如何在字符串中使用json执行聚合mongo查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆