一、更新并返回更新后的值
Object newVal = mongoTemplate.findAndModify(query, update, FindAndModifyOptions.options().returnNew(true), Object.class, collectionName);
二、批量操作
BulkOperations bulkOps = mongoTemplate.bulkOps(BulkOperations.BulkMode.ORDERED, Object.class, collectionName); Objects.parallelStream().forEach(fieldId -> { Criteria criteria = Criteria.where("parentDocColumnId").is("xxxx"); criteria.and("parentDocColumn.childDocColumn").is("xxx"); bulkOps.updateOne(Query.query(criteria), update); }); bulkOps.execute();
三、聚合统计操作
Criteria criteria = Criteria.where("_id").is(id).and("xxx").is(xxx); GroupOperation groupOperation = Aggregation.group("groupName1","groupName2").count().as("count"); Aggregation aggregation = Aggregation.newAggregation(Aggregation.match(criteria),groupOperation); AggregationResults
四、mongodb shell 对子文档简单分页设计
文档结构如下:
{
"_id" : ObjectId("58ce336652dcaf34e4e240af"),
"name" : "三年二班",
"code" : "20170302",
"students" : [
{
"id" : 1,
"name" : "小明",
"age" : 9
},
{
"id" : 2,
"name" : "小刘",
"age" : 10
},
{
"id" : 3,
"name" : "小红",
"age" : 8
},
{
"id" : 4,
"name" : "小王",
"age" : 9
},
{
"id" : 5,
"name" : "小孙",
"age" : 11
},
{
"id" : 6,
"name" : "小周",
"age" : 8
},
{
"id" : 7,
"name" : "小林",
"age" : 10
},
{
"id" : 8,
"name" : "小龙",
"age" : 12
},
{
"id" : 9,
"name" : "小曲",
"age" : 9
},
{
"id" : 10,
"name" : "小金",
"age" : 7
}
]
}
// 只显示某个字段,并不显示某个字段
db.getCollection('Class').find({},{"students":1,"_id":0})
db.getCollection('Class').aggregate([{$unwind:"$students"},{$match:{"students.name":"小明","students.age":{"$gt":8}}}])
db.getCollection('Class').aggregate([{$project:{_id:0, students:1}},{$unwind:"$students"},{$match:{"students.name":"小明","students.age":{"$gt":8}}}])
db.getCollection('Class').aggregate([{$project:{_id:0, students:1}},{$unwind:"$students"},{$match:{"students.age":{"$gt":8}}},{$group:{_id:null,count:{$sum:1}}}]).pretty()
db.eval("queryStudentCount(args)")
db.eval("queryStudentList(args,offset,pagesize)")
function(age,offset,pagesize) {
//var start = new Date()
// for(var i=0; i<200000; i++){
// db.Class.insert({_id:i,number:i})
//}
// var end = new Date()
// end-start// write your code here
var obj = db.getCollection('Class').aggregate([{$project:{_id:0, students:1}},{$unwind:"$students"},{$match:{"students.age":{"$gt":age}}},{$skip:offset},{$limit:pagesize},{"$sort":{"age":1}}]).pretty();
return obj;
}
function(age) {
//var start = new Date()
// for(var i=0; i<200000; i++){
// db.Class.insert({_id:i,number:i})
//}
// var end = new Date()
// end-start// write your code here
var obj = db.getCollection('Class').aggregate([{$project:{_id:0, students:1}},{$unwind:"$students"},{$match:{"students.age":{"$gt":age}}},{$group:{_id:0,count:{$sum:1}}}]).pretty();
return obj;
}