1. Combine query according to in, eq, lte and other conditions, and add sort and limit at the same time
1, native
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);
2. Perform the update operation to update a single document
1, native
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);
3. Update the document with findAndModify command and return the updated document (only for a single document)
1, native
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 );
IV. aggregation operation (according to a field group, a field in the document is merged into the array, and the first element in the array is taken at last)
1, native
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 );