mongoDB原生查询与spring data mongoDB的映射

一、按照in、eq、lte等条件组合查询,同时添加sort和limit
1、原生

db.message.find(
    {  receiverRoleId: {$in: [1381073, 1381073]}, 
       resourceType:3, 
       sendTime: {$lte: 1523355918300}
    })
    .sort({sendTime: -1 })
    .limit(10);

2、spring data mongoDB

Criteria criteria = Criteria.where("receiverRoleId").in(receiverRoleIds)
                .and("readState").is(readState.getIndex())
                .and("sendTime").lte(sendTime);
Query query = Query.query(criteria);
query.with(new Sort(Sort.Direction.DESC, "sendTime"));
query.limit(count);
mongoTemplate.find(query, Notification.class);

二、执行update操作,更新单个文档
1、原生

db.message.update(
    {_id: 586537, readState: 2}, 
    {$set: {readState: 1}}, 
    {multi: false}
);

2、spring data mongoDB

Criteria criteria = Criteria.where("_id").is(id).and("readState").is(ReadState.UNREAD.getIndex());
Query query = Query.query(criteria);
Update update = Update.update("readState", ReadState.READ.getIndex());
mongoTemplate.updateFirst(query, update, Notification.class);

三、通过findAndModify命令更新文档并且返回更新之后的文档(只能作用于单个文档)
1、原生

db.message.findAndModify({
    query: {_id: 586537, readState: 2}, 
    update: {$set: {publishType: 1}}, 
    new: true
});

2、spring data mongoDB

Query query = Query.query(Criteria.where("_id").is(2).and("readState").is(2));
Update update = Update.update("publishType", 1);
Notice updateResult = mongoTemplate.findAndModify(
        query,
        update,
        FindAndModifyOptions.options().returnNew(true), 
        Notice.class
);

四、聚合操作(根据某一字段group,并且将文档中的某一字段合并到数组中,最后取数组中的第一个元素)
1、原生

db.message.aggregate([
    { $match: {toAffairId : {$in: [590934, 591016]}} }, 
    { $sort: {sendTime: -1} },
    { $group: {_id: "$toAffairId", contents: {$push: "$content"}} },
    { $project: {_id: 0, "affaiId": "$_id", contents: {$slice: ["$contents", 1]} } }
]);

2、spring data mongoDB

Criteria criteria = Criteria.where("toAffairId").in(affairIds);
Aggregation aggregation = Aggregation.newAggregation(
    match(criteria),
    sort(Sort.Direction.DESC, "sendTime"),
    group("toAffairId").push("content").as("contents"),
AggregationResults<MobileDynamicMessageDataModel> results = mongoTemplate.aggregate(
    aggregation, 
    collectionName, 
    MobileDynamicMessageDataModel.class
);

五、数组查询,在某个document中包含数组,对数组进行过滤,并返回数组中第一个符合条件的元素
1、原生

db.audit_record.find(
    { criteriaAuditRecords: {$elemMatch: {personalAuditIds: {$in: [12180209]}}} }
).project({"_id":1, "criteriaAuditRecords.$":1});

2、spring data mongoDB

Criteria criteria = Criteria.where("criteriaAuditRecords").elemMatch(Criteria.where("personalAuditIds").in(personalAuditId));
Query query = Query.query(criteria);        
query.fields().include("_id").include("criteriaAuditRecords.$");
return mongoTemplate.findOne(query, AuditRecord.class);

相关推荐