mongoDB原生查詢與spring data mongoDB的映射

1、按照in、eq、lte等條件組合查詢,同時添加sort和limit
一、原生spring

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

二、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);

2、執行update操做,更新單個文檔
一、原生code

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

二、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);

3、經過findAndModify命令更新文檔而且返回更新以後的文檔(只能做用於單個文檔)
一、原生get

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

二、spring data mongoDBit

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
);

4、聚合操做(根據某一字段group,而且將文檔中的某一字段合併到數組中,最後取數組中的第一個元素)
一、原生io

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]} } }
]);

二、spring data mongoDBclass

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
);

5、數組查詢,在某個document中包含數組,對數組進行過濾,並返回數組中第一個符合條件的元素
一、原生date

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

二、spring data mongoDBim

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);
相關文章
相關標籤/搜索