在Java中构建MongoDB查询
这是在mongo shell中工作的查询,我正在尝试用Java动态地重新创建它:在Java中构建MongoDB查询,java,mongodb,Java,Mongodb,这是在mongo shell中工作的查询,我正在尝试用Java动态地重新创建它: db.contacts.find( { $and: [ {"site" : { $in : ["FR", "NL"] }}, {"country" : {$in : ["Belgium"]}} ] } ); 我将我的站点和国家的值存储在String[]中,如下所示: String[] sites = {"NL", "
db.contacts.find(
{
$and: [
{"site" : { $in : ["FR", "NL"] }},
{"country" : {$in : ["Belgium"]}}
]
}
);
我将我的站点和国家的值存储在String[]
中,如下所示:
String[] sites = {"NL", "FR"};
String[] countries = {"Belgium"};
我的查询生成器如下所示:
Document query = new Document();
Document st = new Document();
Document ct = new Document();
List<Document> lst = new ArrayList<>();
if(sites != null){
st.put("site", new Document("$in", Arrays.asList(sites)));
lst.add(st);
}
if(countries != null){
ct.put("country", new Document("$in", Arrays.asList(countries)));
lst.add(ct);
}
query.put("$and", lst);
但是这个查询没有返回任何结果,而我粘贴在顶部的查询效果很好
如果我这样运行查询:
Document{{$and=[Document{{site=Document{{$in=[NL, FR]}}}}]}}
它只返回NL标记为site的文档,但不返回FR,反之亦然。如果FR在数组中的NL之前,它将只返回FR而不返回NL文档
编辑:我想出来了!基本上,它不喜欢转换数组。asList(sites),我必须像这样初始化新列表:
List List List=new ArrayList(Arrays.asList(sites))代码>并且它按预期工作 能否尝试对两个过滤器重新使用相同的对象?以下是一个例子:
BasicDBObject whereCondition = new BasicDBObject();
whereCondition.put("site", new BasicDBObject("$in", Arrays.asList(sites)));
whereCondition.put("country", new BasicDBObject("$in", Arrays.asList(countries)));
//execute the query
无法复制。我用Java测试了您的查询,结果与预期一致-返回NL和FR。您使用的是什么版本的mongo驱动程序,您的mongoDB版本是什么?驱动程序是3.2.2,mongoDB是3.2.3需要一个有效的$and语句,它需要一个数组[]。您可以发布查询mongo的方法的完整代码吗?就是这样,生成查询后,我所做的就是:contacts.find(查询)代码>嗯。。您能检查一下您的应用程序是否与您查询的mongo数据库连接到同一个mongo数据库吗?是的,它已连接,显然没有使用数组。asList我必须初始化List并使用它。解决了。谢谢
BasicDBObject whereCondition = new BasicDBObject();
whereCondition.put("site", new BasicDBObject("$in", Arrays.asList(sites)));
whereCondition.put("country", new BasicDBObject("$in", Arrays.asList(countries)));
//execute the query