由于 com.mongodb.BasicDBObject 添加多个条件 GridFSDBFile 查询时异常的限制 [英] Due to limitations of the com.mongodb.BasicDBObject exception when add multiple criteria GridFSDBFile query

查看:30
本文介绍了由于 com.mongodb.BasicDBObject 添加多个条件 GridFSDBFile 查询时异常的限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 GridFSDBFile 中添加多个条件,我已经迭代了地图并形成了条件对象,但我遇到了以下异常

I want add multiple criteria in GridFSDBFile, I have iterated the map and formed the criteria object but i am getting following exception

由于 com.mongodb.BasicDBObject 的限制,不能添加指定了第二个$and"表达式.

Due to limitations of the com.mongodb.BasicDBObject, you can't add a second '$and' expression specified.

我的代码片段是

public void getFile(Map<String, Object> metaData) throws Exception {
    Criteria criteria = new Criteria();
    metaData.forEach((k, v) -> criteria.andOperator(Criteria.where("metadata." + k).is(v)));
    GridFSDBFile gridFSDBFile = gridFsOperations.findOne(new Query(criteria));
    if (gridFSDBFile == null) {
        throw new HttpConflictException();
}

推荐答案

您可以将方法更新到下面.您正在尝试提供多个 $and 运算符,每个运算符都有一个条件.

You can update method to below. You are trying to provide multiple $and operator with each having a criteria.

顺便说一句,你不需要显式的 anding,因为 mongodb 提供隐式的 anding 当条件用逗号分隔时.

Btw, you don't need an explicit anding as mongodb provides implicit anding when criteria is separated by comma.

public void getFile(Map<String, Object> metaData) throws Exception {
    Criteria criteria = new Criteria();
    metaData.forEach((k, v) -> criteria.and("metadata." + k).is(v));
    GridFSDBFile gridFSDBFile = gridFsOperations.findOne(new Query(criteria));
    if (gridFSDBFile == null) {
        throw new HttpConflictException();
}

在需要显式ing的情况下,可以使用下面的代码

In cases where you need explicit anding, you can use below code

public void getFile(Map<String, Object> metaData) throws Exception {
    Criteria criteria = new Criteria();
     List<Criteria> andExpressions = metaData.entrySet().stream().
            map(kv -> Criteria.where("data." + kv.getKey()).is(kv.getValue())).
            collect(toList());
    Query andQuery = new Query();
    Criteria andCriteria = new Criteria();
    andQuery.addCriteria(andCriteria.andOperator(andExpressions.toArray(new Criteria[andExpressions.size()])));
    GridFSDBFile gridFSDBFile = gridFsOperations.findOne(andQuery);
    if (gridFSDBFile == null) {
        throw new HttpConflictException();
}

这篇关于由于 com.mongodb.BasicDBObject 添加多个条件 GridFSDBFile 查询时异常的限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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