Implementation of java Code for embedded Array query in mongodb

I use the following code on Robo 3T (a mongodbGUI software)

db.getCollection("json").find({"time":{$gte:1528771648859,$lte:1528771698869}},{"data":{$elemMatch :{"deviceid":456789123}}})

can get the results I want, but I can"t use the code

        BasicDBObject query = new BasicDBObject();
        query.put("time",(new BasicDBObject("$gte",1528771648859L)).append("$lte",1528771698869L));
        query.put("data",new BasicDBObject("$elemMatch",new BasicDBObject("deviceid",456789123)));
        DBCursor dbCursor = mongoTemplate.getCollection("json").find(query);

I would like to ask you guys, how can I use java to implement the above sql statement and return the correct results?


first of all, what is written in Robot 3T is not correct. The signature of the find method is

db.<>.find(<>, <>, <>);

{"data": {$elemMatch: {"deviceid": 456789123} already belongs to the projection parameter, although it will not report an error, it is certainly not the result you want. Your equivalent condition is only {"time": {$gte:1528771648859,$lte:1528771698869}} , so the result is found. The code for
Java is correct instead. But because of one more condition, we can't find out the result.

Menu