在spring mongo db query中指定多个条件

时间:2017-08-16 17:00:19

标签: mongodb spring-data spring-data-mongodb

我正在遍历键/值对列表并对每个键/值执行find。我可以在sql中创建一个单独的查询文档,以便只有一个数据库调用。

    List<User> userList = new ArrayList<User>();
    for (Map accounts:attributes) {
        Query query = new Query();
        List<Criteria> andCriteriaList = new ArrayList<Criteria>();
        accounts.forEach((key, value) -> {
            Criteria criteria = Criteria.where((String) key).is(value);
            andCriteriaList.add(criteria);
        });
        query.addCriteria(new Criteria().andOperator(andCriteriaList.toArray(new Criteria[andCriteriaList.size()])));
        if (mongoTemplate.exists(query, User.class)) {
            userList.add((User)mongoTemplate.find(query, User.class));
            //System.out.println(mongoTemplate.find(query, User.class));
        }

谢谢,

2 个答案:

答案 0 :(得分:4)

您可以重构代码以创建$or表达式。无需明确$and运算符。

这样的东西
 Query orQuery = new Query();
 Criteria orCriteria = new Criteria();
 List<Criteria> orExpression =  new ArrayList<>();
 for (Map<String, Object> accounts : attributes) {
   Criteria expression = new Criteria();
   accounts.forEach((key, value) -> expression.and(key).is(value));
   orExpression.add(expression);
 }
 orQuery.addCriteria(orCriteria.orOperator(orExpression.toArray(new Criteria[orExpression.size()])));
 List<User> userList = mongoOperations.find(orQuery, User.class);

这应输出类似

的查询
{ "$or" : [{ "key1" : "value1", "key2" : "value2" }, { "key3" : "value3", "key4" : "value4" }] }

答案 1 :(得分:2)

如果你想用下面的值查询多个字段(field1, field2, ....) 是解决方案

Query query = new Query();
List<Criteria> criteria = new ArrayList<>();

criteria.add(Criteria.where(field1).is(field1val));
criteria.add(Criteria.where(field2).is(field2val));
// you can add all your fields here as above

query.addCriteria(new Criteria().andOperator(criteria.toArray(new Criteria[criteria.size()])));
List<JSONObject> filteredVals = mongoOperations.find(query, JSONObject.class);

上面返回的filteredVals是JSONObject