ㄓㄤㄑㄧㄤ

$elemMatch使用

db.getCollection('Persion').find({"relatives":{"$elemMatch":{"name": "赵刚", "relationship": 0}}})
db.hjls_hall_schdule_config.find({"dates.month":202305},{"dates":{"$elemMatch":{"date":20230529}}});

数据如下

{
    "_id" : ObjectId("5e6b4ef546b5f44e5c5b276d"),
    "name" : "赵小明",
    "used_name" : [ 
        "赵明", 
        "赵小朋"
    ],
    "age" : 16,
    "gender" : 0,
    "relatives" : [ 
        {
            "name" : "赵刚",
            "relationship" : 0
        }, 
        {
            "name" : "秀英",
            "relationship" : 1
        }
    ]
}

 mongoTemplate写法一

Query query = new Query();
query.addCriteria(Criteria.where("year").is(year).and("month").is(month));
query.fields().elemMatch("dates", (Criteria.where("date").is(date).and("city").is(city)));
HallSchduleConfigDoc doc = mongoTemplate.findOne(query, HallSchduleConfigDoc.class);

mongoTemplate写法二

Query query = new Query();
    query.addCriteria(Criteria.where("year").is(year).and("month").is(month))
              .addCriteria(
                  Criteria.where("dates")
                      .elemMatch(Criteria.where("date").is(date).and("city").is(city)));
    query.fields().include("dates.$");
    HallSchduleConfigDoc doc = mongoTemplate.findOne(query, HallSchduleConfigDoc.class);

 

posted @ 2022-12-01 10:40  ㄓㄤㄑㄧㄤ  阅读(68)  评论(0编辑  收藏  举报
哈哈,页脚部分。