提问者:小点点

将mongo命令传输到Java但它不起作用


mongo命令:

db.tissue_source.aggregate([{
$match:{

        "tissue_backups.23c5bd57da4e461caae0bbf2b06997b8": {
            $all: [{
                    $elemMatch: {
                        "63173253349670": {
                            $regex: ".*?正常.*"
                        }
                    }
                }, {
                    $elemMatch: {
                        "63173253349670": {
                            $regex: ".*?出库.*"
                        }
                    }
                }
            ]
        }
               
}
}])

命令可以在mongo客户端成功运行:

转入Java:

BasicDBObject match = new BasicDBObject("$match",
                new BasicDBObject("tissue_backups.23c5bd57da4e461caae0bbf2b06997b8",
                        new BasicDBObject("$all", Arrays.asList(
                                new BasicDBObject("$elemMatch",
                                        new BasicDBObject("63173253349670", "正常")),
                                new BasicDBObject("$elemMatch",
                                        new BasicDBObject("63173253349670", "出库"))
                        ))
                )
        );

当我使用聚合查询时

......
......
dbObjectList.add(match);
Cursor aggregateOutput = MongoKit.getCollection(collectionName).aggregate(dbObjectList, AggregationOptions.builder()
                .allowDiskUse(true)
                .build());

它抛出异常如下:

命令失败,服务器127.0.0.1:27017上出现错误2:$or/$and/$nor条目需要是完整的对象。完整的响应是{"ok": 0.0,"errmsg":"$or/$and/$nor条目需要是完整的对象","code":2,"codeName":"BadValue"}

我打印BasicDBObject内容,与命令相同:

System.out.println(match.toJson());

{ "$match" : { "$or" : [{ "$or" : [{ "tissue_backups.23c5bd57da4e461caae0bbf2b06997b8" : { "$all" : [{ "$elemMatch" : { "63173253349670" : { "$regex" : ".*?正常.*" } } }, { "$elemMatch" : { "63173253349670" : { "$regex" : ".*?出库.*" } } }] } }] }] } }

共1个答案

匿名用户

您可以尝试稍微简化该查询:

db.collection.aggregate([
  {$match: 
     {$and: [
        {"tissue_backups.23c5bd57da4e461caae0bbf2b06997b8.63173253349670": 
            {$regex: ".*?正常.*"}
        },
        {"tissue_backups.23c5bd57da4e461caae0bbf2b06997b8.63173253349670": 
            {$regex: ".*?出库.*"}
        }
     ]}
  }
])

(请参阅Playground中的查询)

然后在Java:

BasicDBObject match = new BasicDBObject("$match",
  new BasicDBObject("$and", Arrays.asList( 
    new BasicDBObject("tissue_backups.23c5bd57da4e461caae0bbf2b06997b8.63173253349670",
      new BasicDBObject("$regex",".*?正常.*")
    ),
    new BasicDBObject("tissue_backups.23c5bd57da4e461caae0bbf2b06997b8.63173253349670",
      new BasicDBObject("$regex",".*?出库.*")
    ),
  ))
)