mongo 内嵌文档查询并过滤 java实现

话不多说,直接上代码。  这是我mongo内的存储结构如下,我现在需要查找的是

tagName =TT01,targetId=13  并且 timeValueList 这个数组中的 time在我查找的范围内的数据。

{ 
    "_id" : ObjectId("5e95851ed78d591eec820e2b"), 
    "serial" : "zth_test", 
    "label" : "wendu", 
    "tagName" : "TT01", 
    "time" : NumberLong(1580879744), 
    "value" : "1485", 
    "targetId" : NumberInt(13), 
    "timeValueList" : [
        {
            "time" : NumberLong(1580879744), 
            "value" : "1485"
        }, 
        {
            "time" : NumberLong(1580879745), 
            "value" : "1485", 
            "_class" : "io.renren.common.model.TimeValue"
        }, 
        {
            "time" : NumberLong(1580879746), 
            "value" : "1485", 
            "_class" : "io.renren.common.model.TimeValue"
        }
}

我百度了别人的博客看过官网后,java实现。

 Query query = new Query();
        query.addCriteria(Criteria.where("targetId").is(targetId).andOperator(Criteria.where("tagName").in(tagName)));
        query.addCriteria(Criteria.where("timeValueList").elemMatch(Criteria.where("time").gte(startTime).andOperator(Criteria.where("time").lte(endTime))));
        /**
         * 组装成的sql语句
         * db.getCollection("history").find({"tagName":"TT01","targetId":13},                                    {"timeValueList":{$elemMatch:{"time":{$gte:1580879744,$lte:1580879746}}}})
         */
        List historyData = mongoTemplate.find(query, HistoryData.class, MongoCollection.HISTORY);

 

你可能感兴趣的:(java,mongo)