一帆磨砺

生活所迫,一叶孤舟

0%

MongoTemplate_SpringBoot

本文Demo位于JavaPractice中的MongoTemplate

环境准备

pom依赖
1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

SpringBoot 依赖

1
2
3
4
5
6
7
8
9
10
11
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
mongo配置
1
2
3
4
5
6
#单服务器,无用户名密码设置
spring.data.mongodb.uri=mongodb://ip地址:端口号/使用数据库名称
#单服务器,有用户名密码设置
spring.data.mongodb.uri=mongodb://用户名:密码@ip地址:端口号/使用数据库名称
#多服务器,集群
#spring.data.mongodb.uri=mongodb://用户名:密码@服务器 1 ip地址:服务器 1 端口,(英文逗号分隔)ip2:port2/使用数据库名称

基本操作

insert(Object objectToSave)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
* 插入mongo方式1
*
* @param req 请求参数
* @return 返回请求结果
*/
@RequestMapping(value = "insertIntoMongoFunc1", method = RequestMethod.POST)
@ApiOperation(notes = "insert(Object objectToSave)", value = "插入mongo方式1", produces =
"application/json")
public String insertIntoMongoFunc1(@RequestBody JSONObject req) {
//此处未指定collection名称,将会插入对象className的collection中,若此collection不存在,则创建
//此处插入的collection名称为jSONObject
mongoTemplate.insert(req);
return successMsg();
}

请求参数:

1
2
3
{
"testInsertMongo1" : "func1"
}

执行结果:
insert(Object objectToSave)

源码查看:

1
2
3
4
5
6
7
8
9
//MongoTemplate 784
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.MongoOperations#insert(java.lang.Object)
*/
public void insert(Object objectToSave) {
ensureNotIterable(objectToSave);
insert(objectToSave, determineEntityCollectionName(objectToSave));
}

由上方源码,ensureNotIterable(objectToSave)是用来确保objectToSave不是数组或者是可遍历的对象集合,如ListCollectionIterator。追踪源码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
...
private static final Collection<String> ITERABLE_CLASSES;

static {

Set<String> iterableClasses = new HashSet<String>();
iterableClasses.add(List.class.getName());
iterableClasses.add(Collection.class.getName());
iterableClasses.add(Iterator.class.getName());

ITERABLE_CLASSES = Collections.unmodifiableCollection(iterableClasses);
}
...
protected void ensureNotIterable(Object o) {
if (null != o) {
if (o.getClass().isArray() || ITERABLE_CLASSES.contains(o.getClass().getName())) {
//此处注释为JanWarlen添加,个人很好奇如果使用List等类的衍生类,如ArrayList会发生什么,有兴趣的同学可以自己试验一下,欢迎评论告知实验结果
throw new IllegalArgumentException("Cannot use a collection here.");
}
}
}

通过类型校验之后调用了:

1
2
3
4
5
6
7
8
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.MongoOperations#insert(java.lang.Object, java.lang.String)
*/
public void insert(Object objectToSave, String collectionName) {
ensureNotIterable(objectToSave);
doInsert(collectionName, objectToSave, this.mongoConverter);
}

可以看出我们将通过**determineEntityCollectionName(objectToSave)**得到将存储在mongo的collection名称,接着调用 doInsert完成数据插入。
//主要是再继续深入源码,作者的功力略显不够,只能到此为止,有兴趣的同学可以深入看看
综上,关于Insert我们得出:

1
2
1、 保存数据的对象类型不可为**List**、**Collection**、**Iterator**;
2、 不指定存储的collection名称,将会使用数据对象的className作为collection名称,并且依据mongo特性,若此collection不存在将会被创建

以下为未展示源码追踪结论:

1
2
1、 若传入String,则必须为Json格式字符串,否则将会抛出MappingException
...待补充,尤其是determineEntityCollectionName和doInsert,欢迎评论
insert(Object objectToSave, String collectionName)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
* 插入mongo方式2
*
* @param req 请求参数
* @return 返回请求结果
*/
@RequestMapping(value = "insertIntoMongoFunc2", method = RequestMethod.POST)
@ApiOperation(notes = "insert(Object objectToSave, String collectionName)", value = "插入mongo方式2", produces =
"application/json")
public String insertIntoMongoFunc2(@RequestBody JSONObject req) {
//将对象插入指定的collection中
mongoTemplate.insert(req, "test");
return successMsg();
}

请求参数:

1
2
3
{
"test" : "testValue123"
}

执行结果:
insert(Object objectToSave, String collectionName)
源码查看:
与2.1.1基本一致,跳过

insert(Collection batchToSave, Class entityClass)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
* 插入mongo方式3
*
* @param req 请求数组
* @return 返回成功
*/
@RequestMapping(value = "insertIntoMongoFunc3", method = RequestMethod.POST)
@ApiOperation(notes = "insert(Collection<? extends Object> batchToSave, Class<?> entityClass)", value =
"插入mongo方式3", produces = "application/json")
public String insertIntoMongoFunc3(@RequestBody JSONArray req) {
//此处未指定collection名称,将会插入对象className的collection中,若此collection不存在,则创建.此处为集合批量插入
//此处插入的collection名称为jSONArray,插入数据条数为JSONArray数组大小
mongoTemplate.insert(req, JSONArray.class);
return successMsg();
}

请求参数:

1
2
3
4
5
6
7
[
{
"name": "1"
},{
"name": "2"
}
]

执行结果:
insert(Collection batchToSave, Class entityClass)
源码查看:

1
2
3
public void insert(Collection<? extends Object> batchToSave, Class<?> entityClass) {
doInsertBatch(determineCollectionName(entityClass), batchToSave, this.mongoConverter);
}

需注意此处的entityClass并没有要求和batchToSave类型一致,并且此处的entityClass仅是获取将要存储的collection名称用。(结论未经试验验证,仅阅读源码推断)

尚未研究透彻,待后续……

insert(Collection batchToSave, String collectionName)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
* 插入mongo方式4
*
* @param req 请求数组
* @return 返回成功
*/
@RequestMapping(value = "insertIntoMongoFunc4", method = RequestMethod.POST)
@ApiOperation(notes = "insert(Collection<? extends Object> batchToSave, String collectionName)", value =
"插入mongo方式4", produces = "application/json")
public String insertIntoMongoFunc4(@RequestBody JSONArray req) {
//将对象插入指定的collection中,此处为集合批量插入
mongoTemplate.insert(req, "test2");
return successMsg();
}

请求参数:

1
2
3
4
5
6
7
[
{
"testJsonobj" : "testValue1"
},{
"testJsonobj" : "testValue2"
}
]

执行结果:
insert(Collection batchToSave, String collectionName)

insertAll(Collection objectsToSave)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@RequestMapping(value = "insertIntoMongoFunc5", method = RequestMethod.GET)
@ApiOperation(notes = "insertAll(Collection<? extends Object> objectsToSave)", value =
"插入mongo方式5", produces = "application/json")
public String insertIntoMongoFunc5() {
List<Object> list = new ArrayList<>();
Student student = new Student();
student.setGrade(1);
student.setId("1234567890");
student.setName("小明");
Teacher teacher = new Teacher();
teacher.setId("0987654321");
teacher.setName("老王");
teacher.setSubject("physics");
list.add(student);
list.add(teacher);
//在list中的每个对象分别插入对象class类名的collection中,逐条
mongoTemplate.insertAll(list);
return successMsg();
}

请求参数:

1

执行结果:
student
teacher

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* 此方法为异常方法,因使用错误变量类型
*
* @param req 请求数组
* @return 返回成功
*/
@RequestMapping(value = "insertIntoMongoFunc6", method = RequestMethod.POST)
@ApiOperation(notes = "insertAll(Collection<? extends Object> objectsToSave)", value =
"插入mongo方式5(异常)", produces = "application/json")
public String insertIntoMongoFunc6(@RequestBody JSONArray req) {
//此处直接使用JSONArray会抛出异常,org.springframework.dao.InvalidDataAccessApiUsageException: No PersistentEntity
// information found for class java.util
// .LinkedHashMap,猜测应该是JSONArray中的JSONObject在@RequestBody映射(?不太确定用词是否准确)时并没有转换为JSONObject,
// 而是转换为了LinkedHashMap,另关于其他Map类型是否会出现同样错误未曾实验,源码阅读出现未能理解代码,希望有同学能够解惑
mongoTemplate.insertAll(req);
return successMsg();
}

请求参数:

1
2
3
4
5
6
7
[
{
"testJsonobj" : "testValue1"
},{
"testJsonobj" : "testValue2"
}
]

执行结果:
插入mongo方式5(异常)ide
debug调试:
插入mongo方式5(异常)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

/**
* 测试insertAll方法使用jsonArray中包含jsonObj效果
*
* @return 返回成功
*/
@RequestMapping(value = "insertIntoMongoFunc7", method = RequestMethod.GET)
@ApiOperation(notes = "insertAll(Collection<? extends Object> objectsToSave)", value =
"插入mongo方式5(测试JSONObject)", produces = "application/json")
public String insertIntoMongoFunc7() {
JSONArray list = new JSONArray();
JSONObject first = new JSONObject();
first.put("testJsonobj", "testValue1");
JSONObject second = new JSONObject();
second.put("testJsonobj", "testValue2");
list.add(first);
list.add(second);
mongoTemplate.insertAll(list);
return successMsg();
}

请求参数:

1

执行结果:
插入mongo方式5(测试JSONObject)

save(Object objectToSave)
1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* 使用save
* @param req 请求
* @return 返回成功
*/
@RequestMapping(value = "saveIntoMongoFunc1", method = RequestMethod.POST)
@ApiOperation(notes = "save(Object objectToSave)", value = "插入mongo方式6", produces = "application/json")
public String saveIntoMongoFunc1(@RequestBody JSONObject req) {
//save 方法同样使用mappingContext.getPersistentEntity(type),但与insertAll不同的是,此处不针对对象内部对象
//预计使用jsonArray将会插入一条数据在jSONArray的collection中
mongoTemplate.save(req);
return successMsg();
}

请求参数:

1
2
3
{
"name" : "saveObj1"
}

执行结果:
save(Object objectToSave)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
    /**
* 测试save保存JSONArray
* @param req 请求
* @return 返回成功
*/
@RequestMapping(value = "saveIntoMongoFunc2", method = RequestMethod.POST)
@ApiOperation(notes = "save(Object objectToSave)", value = "测试保存JSONArray", produces = "application/json")
public String saveIntoMongoFunc2(@RequestBody JSONArray req) {
//java.lang.ClassCastException: com.mongodb.BasicDBObject cannot be cast to com.mongodb.BasicDBList
// mongoTemplate.save(req);

//相同异常
List<Object> list = new ArrayList<>();
Student student = new Student();
student.setGrade(1);
student.setId("1234567890");
student.setName("小明");
Teacher teacher = new Teacher();
teacher.setId("0987654321");
teacher.setName("老王");
teacher.setSubject("physics");
list.add(student);
list.add(teacher);
mongoTemplate.save(list);
return successMsg();
}

请求参数:

1
2
3
4
5
6
7
8
9
[
{
"testJsonobj" : "testValue1"
},{
"testJsonobj" : "testValue2"
}
]


执行结果:
saveIntoMongoFunc2
源码查看:
异常位于MappingMongoConverter的393行

1
2
3
4
5
6
7
8
...
protected void writeInternal(final Object obj, final DBObject dbo, final TypeInformation<?> typeHint) {
...
if (Collection.class.isAssignableFrom(entityType)) {
writeCollectionInternal((Collection<?>) obj, ClassTypeInformation.LIST, (BasicDBList) dbo);
return;
}
...

此处不是很明白,如果不支持,可以选择与2.1.1中的ensureNotIterable进行类型过滤,此处没有类型过滤,但是却在**(BasicDBList) dbo强转的时候抛出异常,在writeInternal方法声明的时候,已经将dbo**定位DBObject,再根据异常提示信息
java.lang.ClassCastException: com.mongodb.BasicDBObject cannot be cast to com.mongodb.BasicDBList,就让人十分不解,不知道此处支持的集合类型有哪些。

save(Object objectToSave, String collectionName)
1
2
3
4
5
6
7
8
9
10
11
/**
* 指定collection存储对象
* @param req 请求
* @return 返回成功
*/
@RequestMapping(value = "saveIntoMongoFunc3", method = RequestMethod.POST)
@ApiOperation(notes = "save(Object objectToSave, String collectionName)", value = "插入mongo方式7", produces = "application/json")
public String saveIntoMongoFunc3(@RequestBody JSONObject req) {
mongoTemplate.save(req,"test2");
return successMsg();
}

请求参数:

1
2
3
{
"save" : "valueTest"
}

执行结果:
save(Object objectToSave, String collectionName)

查询数据基础
  • jSONArray
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    /* 1 */
    {
    "_id" : ObjectId("5a4f2c05e6bd285cc1c3ad0b"),
    "_class" : "java.util.LinkedHashMap",
    "name" : "1"
    }

    /* 2 */
    {
    "_id" : ObjectId("5a4f2c05e6bd285cc1c3ad0c"),
    "_class" : "java.util.LinkedHashMap",
    "name" : "2"
    }
  • jSONObject
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    /* 1 */
    {
    "_id" : ObjectId("5a4f1a2de6bd285cc1c3ad09"),
    "_class" : "com.alibaba.fastjson.JSONObject",
    "testInsertMongo1" : "func1"
    }

    /* 2 */
    {
    "_id" : ObjectId("5a5034fee6bd28102724317e"),
    "_class" : "com.alibaba.fastjson.JSONObject",
    "testJsonobj" : "testValue1"
    }

    /* 3 */
    {
    "_id" : ObjectId("5a5034fee6bd28102724317f"),
    "_class" : "com.alibaba.fastjson.JSONObject",
    "testJsonobj" : "testValue2"
    }

    /* 4 */
    {
    "_id" : ObjectId("5a503d85e6bd282163fd99dd"),
    "_class" : "com.alibaba.fastjson.JSONObject",
    "name" : "saveObj1"
    }

    /* 5 */
    {
    "_id" : ObjectId("5a5f078082d92d967e043d75"),
    "test" : []
    }
  • student
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    /* 1 */
    {
    "_id" : "1234567890",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小明1号",
    "grade" : 2,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 2 */
    {
    "_id" : "201801102003",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小明2号",
    "grade" : 1,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }
  • teacher
    1
    2
    3
    4
    5
    6
    7
    /* 1 */
    {
    "_id" : "0987654321",
    "_class" : "com.janwarlen.entity.Teacher",
    "name" : "老王",
    "subject" : "physics"
    }
  • test
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    /* 1 */
    {
    "_id" : ObjectId("59bb97ede2da6021a6cd34ef"),
    "name" : "tiger",
    "sex" : "male",
    "type" : "east north tiger"
    }

    /* 2 */
    {
    "_id" : ObjectId("59bb9803e2da6021a6cd34f0"),
    "name" : "tiger",
    "sex" : "male",
    "type" : "east north tiger",
    "addr" : "123132132"
    }

    /* 3 */
    {
    "_id" : ObjectId("59bb981ee2da6021a6cd34f1"),
    "name" : "tiger",
    "sex" : "male",
    "locat" : "east north tiger",
    "addr" : "123132132"
    }

    /* 4 */
    {
    "_id" : ObjectId("5a4f139ae6bd285395cb44ba"),
    "_class" : "com.alibaba.fastjson.JSONObject",
    "test" : "testValue123"
    }

    /* 5 */
    {
    "_id" : ObjectId("5a5f04d982d92d967e043d02"),
    "testSet" : [
    "tiger"
    ]
    }
  • test2
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    /* 1 */
    {
    "_id" : ObjectId("5a533668e6bd2813e6efb5ac"),
    "_class" : "java.util.LinkedHashMap",
    "testJsonobj" : "testValue1"
    }

    /* 2 */
    {
    "_id" : ObjectId("5a533668e6bd2813e6efb5ad"),
    "_class" : "java.util.LinkedHashMap",
    "testJsonobj" : "testValue2"
    }

    /* 3 */
    {
    "_id" : ObjectId("5a533d7be6bd2813e6efb5ae"),
    "_class" : "com.alibaba.fastjson.JSONObject",
    "save" : "valueTest"
    }
    find(Query query, Class entityClass)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    @RequestMapping(value = "/queryMongoFunc1", method = RequestMethod.GET)
    @ApiOperation(notes = "find(Query query, Class<T> entityClass)", value = "mongo查询1", produces = "application/json")
    public String queryMongoFunc1() {
    Query query = Common.getQueryNormal(1, "小明.号");
    List<Student> jsonObjects = mongoTemplate.find(query, Student.class);
    JSONArray array = new JSONArray();
    array.addAll(jsonObjects);
    return array.toJSONString();
    }
    查询条件:
    1
    db.getCollection('student').find({"grade":1,"name":/小明.号/,"birth":{$lt:ISODate("2018-02-10T12:04:51.367Z"), $gt:ISODate("2018-01-09T12:04:51.367Z")}})
    查询结果:
    1
    2
    3
    4
    5
    6
    7
    8
    [
    {
    "birth": 1515585891367,
    "grade": 1,
    "id": "201801102003",
    "name": "小明2号"
    }
    ]
    find(final Query query, Class entityClass, String collectionName)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    @RequestMapping(value = "/queryMongoFunc2", method = RequestMethod.GET)
    @ApiOperation(notes = "find(final Query query, Class<T> entityClass, String collectionName)", value = "mongo查询2",
    produces = "application/json")
    public String queryMongoFunc2() {
    Query query = Common.getQueryNormal(2, "小明.号");
    List<JSONObject> jsonObjects = mongoTemplate.find(query, JSONObject.class, "student");
    JSONArray array = new JSONArray();
    array.addAll(jsonObjects);
    return array.toJSONString();
    }
    查询条件:
    1
    db.getCollection('student').find({"grade":2,"name":/小明.号/,"birth":{$lt:ISODate("2018-02-10T12:04:51.367Z"), $gt:ISODate("2018-01-09T12:04:51.367Z")}})
    查询结果
    1
    2
    3
    4
    5
    6
    7
    8
    [
    {
    "grade": 2,
    "name": "小明1号",
    "birth": 1515585891367,
    "_id": "1234567890"
    }
    ]
    findById(Object id, Class entityClass)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    @RequestMapping(value = "/queryMongoFunc3", method = RequestMethod.GET)
    @ApiOperation(notes = "findById(Object id, Class<T> entityClass)", value = "mongo查询3", produces =
    "application/json")
    public String queryMongoFunc3() {
    Student res = mongoTemplate.findById("201801102003", Student.class);
    JSONArray array = new JSONArray();
    array.add(res);
    return array.toJSONString();
    }
    查询条件:
    1
    db.getCollection('student').find({"_id":"201801102003"})
    查询结果:
    1
    2
    3
    4
    5
    6
    7
    8
    [
    {
    "birth": 1515585891367,
    "grade": 1,
    "id": "201801102003",
    "name": "小明2号"
    }
    ]
    findById(Object id, Class entityClass, String collectionName)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    @RequestMapping(value = "/queryMongoFunc4", method = RequestMethod.GET)
    @ApiOperation(notes = "findById(Object id, Class<T> entityClass, String collectionName)", value = "mongo查询4",
    produces = "application/json")
    public String queryMongoFunc4() {
    JSONObject res = mongoTemplate.findById("1234567890", JSONObject.class, "student");
    JSONArray array = new JSONArray();
    array.add(res);
    return array.toJSONString();
    }
    查询条件:
    1
    db.getCollection('student').find({"_id":"1234567890"})
    查询结果
    1
    2
    3
    4
    5
    6
    7
    8
    [
    {
    "grade": 2,
    "name": "小明1号",
    "birth": 1515585891367,
    "_id": "1234567890"
    }
    ]
    findOne(Query query, Class entityClass, String collectionName)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    @RequestMapping(value = "/queryMongoFunc6", method = RequestMethod.GET)
    @ApiOperation(notes = "findOne(Query query, Class<T> entityClass, String collectionName)", value = "mongo查询6",
    produces = "application/json")
    public String queryMongoFunc6() {
    JSONObject res = mongoTemplate.findOne(Common.getQueryNormal(1, "小明.号"), JSONObject.class, "student");
    JSONArray array = new JSONArray();
    array.add(res);
    return array.toJSONString();
    }
    查询条件:
    1
    db.getCollection('student').find({"grade":1,"name":/小明.号/,"birth":{$lt:ISODate("2018-02-10T12:04:51.367Z"), $gt:ISODate("2018-01-09T12:04:51.367Z")}})
    查询结果:
    1
    2
    3
    4
    5
    6
    7
    8
    [
    {
    "birth": 1515585891367,
    "grade": 1,
    "id": "201801102003",
    "name": "小明2号"
    }
    ]
    findAll(Class entityClass)
    1
    2
    3
    4
    5
    6
    7
    8
    @RequestMapping(value = "/queryMongoFunc7", method = RequestMethod.GET)
    @ApiOperation(notes = "findAll(Class<T> entityClass)", value = "mongo查询7", produces = "application/json")
    public String queryMongoFunc7() {
    List<Student> res = mongoTemplate.findAll(Student.class);
    JSONArray array = new JSONArray();
    array.addAll(res);
    return array.toJSONString();
    }
    查询条件:
    1
    db.getCollection('student').find({})
    查询结果:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    [
    {
    "birth": 1515585891367,
    "grade": 2,
    "id": "1234567890",
    "name": "小明1号"
    },
    {
    "birth": 1515585891367,
    "grade": 1,
    "id": "201801102003",
    "name": "小明2号"
    }
    ]
    findAll(Class entityClass, String collectionName)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    @RequestMapping(value = "/queryMongoFunc8", method = RequestMethod.GET)
    @ApiOperation(notes = "findAll(Class<T> entityClass, String collectionName)", value = "mongo查询8", produces =
    "application/json")
    public String queryMongoFunc8() {
    List<JSONObject> res = mongoTemplate.findAll(JSONObject.class, "student");
    JSONArray array = new JSONArray();
    array.addAll(res);
    return array.toJSONString();
    }
    查询条件:
    1
    db.getCollection('student').find({})
    查询结果:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    [
    {
    "birth": 1515585891367,
    "grade": 2,
    "id": "1234567890",
    "name": "小明1号"
    },
    {
    "birth": 1515585891367,
    "grade": 1,
    "id": "201801102003",
    "name": "小明2号"
    }
    ]
    updateFirst(Query query, Update update, Class<?> entityClass)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    @RequestMapping(value = "/updateMongoFunc1", method = RequestMethod.GET)
    @ApiOperation(notes = "updateFirst(Query query, Update update, Class<?> entityClass)", value = "mongo修改1",
    produces = "application/json")
    public String updateMongoFunc1() {
    Update update = new Update();
    update.set("grade", 1);
    WriteResult writeResult = mongoTemplate.updateFirst(Common.getQueryNormal(2, "小明2号"), update, JSONObject.class);
    return Common.successMsg(writeResult.getN());
    }
    执行结果:
    before
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    /* 1 */
    {
    "_id" : "1234567890",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小明2号",
    "grade" : 2,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 2 */
    {
    "_id" : "1234567891",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小红",
    "grade" : 2,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 3 */
    {
    "_id" : "201801102003",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小明1号",
    "grade" : 1,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }
    after
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    /* 1 */
    {
    "_id" : "1234567890",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小明2号",
    "grade" : 1,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 2 */
    {
    "_id" : "1234567891",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小红",
    "grade" : 2,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 3 */
    {
    "_id" : "201801102003",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小明1号",
    "grade" : 1,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }
    updateFirst(final Query query, final Update update, final String collectionName)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    @RequestMapping(value = "/updateMongoFunc2", method = RequestMethod.GET)
    @ApiOperation(notes = "updateFirst(final Query query, final Update update, final String collectionName)", value =
    "mongo修改2", produces = "application/json")
    public String updateMongoFunc2() {
    Update update = new Update();
    update.set("grade", 2);
    WriteResult student = mongoTemplate.updateFirst(Common.getQueryNormal(1, "小明2号"), update, "student");
    return Common.successMsg(student.getN());
    }
    执行结果:
    before
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    /* 1 */
    {
    "_id" : "1234567890",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小明2号",
    "grade" : 1,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 2 */
    {
    "_id" : "1234567891",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小红",
    "grade" : 2,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 3 */
    {
    "_id" : "201801102003",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小明1号",
    "grade" : 2,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }
    after
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    /* 1 */
    {
    "_id" : "1234567890",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小明2号",
    "grade" : 2,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 2 */
    {
    "_id" : "1234567891",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小红",
    "grade" : 2,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 3 */
    {
    "_id" : "201801102003",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小明1号",
    "grade" : 2,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }
    updateFirst(Query query, Update update, Class<?> entityClass, String collectionName)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    @RequestMapping(value = "/updateMongoFunc3", method = RequestMethod.GET)
    @ApiOperation(notes = "updateFirst(Query query, Update update, Class<?> entityClass, String collectionName)",
    value = "mongo修改3", produces = "application/json")
    public String updateMongoFunc3() {
    Update update = new Update();
    update.set("grade", 1);
    WriteResult student = mongoTemplate.updateFirst(Common.getQueryNormal(2, "小明2号"), update, Student.class,
    "student");
    return Common.successMsg(student.getN());
    }
    执行结果:
    before
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    /* 1 */
    {
    "_id" : "1234567890",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小明2号",
    "grade" : 2,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 2 */
    {
    "_id" : "1234567891",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小红",
    "grade" : 2,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 3 */
    {
    "_id" : "201801102003",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小明1号",
    "grade" : 2,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }
    after
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    /* 1 */
    {
    "_id" : "1234567890",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小明2号",
    "grade" : 1,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 2 */
    {
    "_id" : "1234567891",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小红",
    "grade" : 2,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 3 */
    {
    "_id" : "201801102003",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小明1号",
    "grade" : 2,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }
    updateMulti(Query query, Update update, Class<?> entityClass)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    @RequestMapping(value = "/updateMongoFunc4", method = RequestMethod.GET)
    @ApiOperation(notes = "updateMulti(Query query, Update update, Class<?> entityClass)", value = "mongo修改4",
    produces = "application/json")
    public String updateMongoFunc4() {
    Update update = new Update();
    update.set("grade", 3);
    WriteResult writeResult = mongoTemplate.updateMulti(Common.getQueryNormal(1, "小明.号"), update, Student.class);
    return Common.successMsg(writeResult.getN());
    }
    执行结果:
    before
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    /* 1 */
    {
    "_id" : "1234567890",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小明2号",
    "grade" : 2,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 2 */
    {
    "_id" : "1234567891",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小红",
    "grade" : 2,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 3 */
    {
    "_id" : "201801102003",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小明1号",
    "grade" : 1,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 4 */
    {
    "_id" : "1234567892",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小明3号",
    "grade" : 1,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 5 */
    {
    "_id" : "1234567894",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小明4号",
    "grade" : 2,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }
    after
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    /* 1 */
    {
    "_id" : "1234567890",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小明2号",
    "grade" : 2,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 2 */
    {
    "_id" : "1234567891",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小红",
    "grade" : 2,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 3 */
    {
    "_id" : "201801102003",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小明1号",
    "grade" : 3,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 4 */
    {
    "_id" : "1234567892",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小明3号",
    "grade" : 3,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 5 */
    {
    "_id" : "1234567894",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小明4号",
    "grade" : 2,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }
    updateMulti(final Query query, final Update update, String collectionName)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    @RequestMapping(value = "/updateMongoFunc5", method = RequestMethod.GET)
    @ApiOperation(notes = "updateMulti(final Query query, final Update update, String collectionName)", value =
    "mongo修改5", produces = "application/json")
    public String updateMongoFunc5() {
    Update update = new Update();
    update.set("grade", 4);
    WriteResult writeResult = mongoTemplate.updateMulti(Common.getQueryNormal(2, "小明.号"), update, "student");
    return Common.successMsg(writeResult.getN());
    }
    执行结果:
    before
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    /* 1 */
    {
    "_id" : "1234567890",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小明2号",
    "grade" : 2,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 2 */
    {
    "_id" : "1234567891",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小红",
    "grade" : 2,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 3 */
    {
    "_id" : "201801102003",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小明1号",
    "grade" : 3,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 4 */
    {
    "_id" : "1234567892",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小明3号",
    "grade" : 3,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 5 */
    {
    "_id" : "1234567894",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小明4号",
    "grade" : 2,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }
    after
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    /* 1 */
    {
    "_id" : "1234567890",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小明2号",
    "grade" : 4,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 2 */
    {
    "_id" : "1234567891",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小红",
    "grade" : 2,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 3 */
    {
    "_id" : "201801102003",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小明1号",
    "grade" : 3,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 4 */
    {
    "_id" : "1234567892",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小明3号",
    "grade" : 3,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 5 */
    {
    "_id" : "1234567894",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小明4号",
    "grade" : 4,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }
    updateMulti(final Query query, final Update update, Class<?> entityClass, String collectionName
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    @RequestMapping(value = "/updateMongoFunc6", method = RequestMethod.GET)
    @ApiOperation(notes = "updateMulti(final Query query, final Update update, Class<?> entityClass, String " +
    "collectionName)", value = "mongo修改6", produces = "application/json")
    public String updateMongoFunc6() {
    Update update = new Update();
    update.set("grade", 1);
    WriteResult writeResult = mongoTemplate.updateMulti(Common.getQueryNormal(3, "小明.号"), update, Student.class,
    "student");
    return Common.successMsg(writeResult.getN());
    }
    执行结果:
    before
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    /* 1 */
    {
    "_id" : "1234567890",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小明2号",
    "grade" : 4,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 2 */
    {
    "_id" : "1234567891",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小红",
    "grade" : 2,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 3 */
    {
    "_id" : "201801102003",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小明1号",
    "grade" : 3,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 4 */
    {
    "_id" : "1234567892",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小明3号",
    "grade" : 3,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 5 */
    {
    "_id" : "1234567894",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小明4号",
    "grade" : 4,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }
    after
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    /* 1 */
    {
    "_id" : "1234567890",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小明2号",
    "grade" : 4,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 2 */
    {
    "_id" : "1234567891",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小红",
    "grade" : 2,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 3 */
    {
    "_id" : "201801102003",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小明1号",
    "grade" : 1,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 4 */
    {
    "_id" : "1234567892",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小明3号",
    "grade" : 1,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 5 */
    {
    "_id" : "1234567894",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小明4号",
    "grade" : 4,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }
    upsert(Query query, Update update, Class<?> entityClass)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    @RequestMapping(value = "/updateMongoFunc7", method = RequestMethod.GET)
    @ApiOperation(notes = "upsert(Query query, Update update, Class<?> entityClass)", value = "mongo修改7", produces =
    "application/json")
    public String updateMongoFunc7() {
    Update update = new Update();
    update.set("grade", 3);
    update.set("name", "upsert1");
    WriteResult upsert = mongoTemplate.upsert(Common.getQueryNormal(3, "小明2号"), update, Student.class);
    return Common.successMsg(upsert.getN());
    }
    执行结果:
    before
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    /* 1 */
    {
    "_id" : "1234567890",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小明2号",
    "grade" : 4,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 2 */
    {
    "_id" : "1234567891",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小红",
    "grade" : 2,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 3 */
    {
    "_id" : "201801102003",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小明1号",
    "grade" : 1,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }
    after
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    /* 1 */
    {
    "_id" : "1234567890",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小明2号",
    "grade" : 4,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 2 */
    {
    "_id" : "1234567891",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小红",
    "grade" : 2,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 3 */
    {
    "_id" : "201801102003",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小明1号",
    "grade" : 1,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 4 */
    {
    "_id" : ObjectId("5a62e4deff7f0e1bec06ac49"),
    "grade" : 3,
    "name" : "upsert1"
    }
    upsert(Query query, Update update, String collectionName)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    @RequestMapping(value = "/updateMongoFunc8", method = RequestMethod.GET)
    @ApiOperation(notes = "upsert(Query query, Update update, String collectionName)", value = "mongo修改8", produces =
    "application/json")
    public String updateMongoFunc8() {
    Update update = new Update();
    update.set("grade", 3);
    update.set("name", "upsert2");
    WriteResult upsert = mongoTemplate.upsert(Common.getQueryNormal(3, "小明2号"), update, "student");
    return Common.successMsg(upsert.getN());
    }
    执行结果:
    before
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    /* 1 */
    {
    "_id" : "1234567890",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小明2号",
    "grade" : 4,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 2 */
    {
    "_id" : "1234567891",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小红",
    "grade" : 2,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 3 */
    {
    "_id" : "201801102003",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小明1号",
    "grade" : 1,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 4 */
    {
    "_id" : ObjectId("5a62e4deff7f0e1bec06ac49"),
    "grade" : 3,
    "name" : "小明2号",
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }
    after
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    /* 1 */
    {
    "_id" : "1234567890",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小明2号",
    "grade" : 4,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 2 */
    {
    "_id" : "1234567891",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小红",
    "grade" : 2,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 3 */
    {
    "_id" : "201801102003",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小明1号",
    "grade" : 1,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 4 */
    {
    "_id" : ObjectId("5a62e4deff7f0e1bec06ac49"),
    "grade" : 3,
    "name" : "upsert2",
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }
    upsert(Query query, Update update, Class<?> entityClass, String collectionName)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    @RequestMapping(value = "/updateMongoFunc9", method = RequestMethod.GET)
    @ApiOperation(notes = "upsert(Query query, Update update, Class<?> entityClass, String collectionName)", value =
    "mongo修改9", produces = "application/json")
    public String updateMongoFunc9() {
    Update update = new Update();
    update.set("grade", 3);
    update.set("name", "upsert3");
    WriteResult upsert = mongoTemplate.upsert(Common.getQueryNormal(3, "小明2号"), update, Student.class, "student");
    return Common.successMsg(upsert.getN());
    }
    执行结果:
    before
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    /* 1 */
    {
    "_id" : "1234567890",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小明2号",
    "grade" : 3,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 2 */
    {
    "_id" : "1234567891",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小红",
    "grade" : 2,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 3 */
    {
    "_id" : "201801102003",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小明1号",
    "grade" : 1,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 4 */
    {
    "_id" : ObjectId("5a62e4deff7f0e1bec06ac49"),
    "grade" : 3,
    "name" : "小明2号",
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }
    after
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    /* 1 */
    {
    "_id" : "1234567890",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "upsert3",
    "grade" : 3,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 2 */
    {
    "_id" : "1234567891",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小红",
    "grade" : 2,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 3 */
    {
    "_id" : "201801102003",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小明1号",
    "grade" : 1,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 4 */
    {
    "_id" : ObjectId("5a62e4deff7f0e1bec06ac49"),
    "grade" : 3,
    "name" : "小明2号",
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }
    findAndModify(Query query, Update update, Class entityClass)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    @RequestMapping(value = "/updateMongoFunc10", method = RequestMethod.GET)
    @ApiOperation(notes = "findAndModify(Query query, Update update, Class<T> entityClass)", value = "mongo修改10",
    produces = "application/json")
    public String updateMongoFunc10() {
    Update update = new Update();
    update.set("grade", 2);
    Student andModify = mongoTemplate.findAndModify(Common.getQueryNormal(1, "小明2号"), update, Student.class);
    return Common.successMsg(andModify);
    }
    执行结果:
    before
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    /* 1 */
    {
    "_id" : "1234567891",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小红",
    "grade" : 2,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 2 */
    {
    "_id" : "201801102003",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小明1号",
    "grade" : 1,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 3 */
    {
    "_id" : ObjectId("5a62e4deff7f0e1bec06ac49"),
    "grade" : 3,
    "name" : "小明2号",
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }
    after
    1
    2
    3
    4
    {
    "res": "success"
    /*接口未返回data,表示未有数据修改*/
    }
    findAndModify(Query query, Update update, Class entityClass, String collectionName)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    @RequestMapping(value = "/updateMongoFunc11", method = RequestMethod.GET)
    @ApiOperation(notes = "findAndModify(Query query, Update update, Class<T> entityClass, String collectionName)",
    value = "mongo修改11",
    produces = "application/json")
    public String updateMongoFunc11() {
    Update update = new Update();
    update.set("grade", 1);
    Student andModify = mongoTemplate.findAndModify(Common.getQueryNormal(2, "小明2号"), update, Student.class,
    "student");
    return Common.successMsg(andModify);
    }
    执行结果:
    before
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    /* 1 */
    {
    "_id" : "1234567891",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小红",
    "grade" : 2,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 2 */
    {
    "_id" : "201801102003",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小明2号",
    "grade" : 2,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 3 */
    {
    "_id" : ObjectId("5a62e4deff7f0e1bec06ac49"),
    "grade" : 3,
    "name" : "小明2号",
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }
    after
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    /*接口返回数据*/
    {
    "res": "success",
    "data": {
    "birth": 1515585891367,
    "grade": 2,
    "id": "201801102003",
    "name": "小明2号"
    }
    }
    /**mongo数据变动**/
    /* 1 */
    {
    "_id" : "1234567891",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小红",
    "grade" : 2,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 2 */
    {
    "_id" : "201801102003",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小明2号",
    "grade" : 1,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 3 */
    {
    "_id" : ObjectId("5a62e4deff7f0e1bec06ac49"),
    "grade" : 3,
    "name" : "小明2号",
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }
    findAndModify(Query query, Update update, FindAndModifyOptions options, Class entityClass)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
        @RequestMapping(value = "/updateMongoFunc12", method = RequestMethod.GET)
    @ApiOperation(notes = "findAndModify(Query query, Update update, FindAndModifyOptions options, Class<T> " +
    "entityClass)",
    value = "mongo修改12",
    produces = "application/json")
    public String updateMongoFunc12() {
    Update update = new Update();
    update.set("grade", 2);
    FindAndModifyOptions options = new FindAndModifyOptions();
    //默认false
    // options.returnNew(true); //是否返回更新后数据
    options.upsert(true); //是否更新(不存在则插入)
    // options.remove(true); //是否删除,为true时不会更新操作,如果returnNew为true则返回旧数据,并且删除
    Student andModify = mongoTemplate.findAndModify(Common.getQueryNormal(1, "小明2号"), update, options, Student
    .class);
    return Common.successMsg(andModify);
    }
    执行结果:
    before
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    /* 1 */
    {
    "_id" : "1234567891",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小红",
    "grade" : 2,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 2 */
    {
    "_id" : "201801102003",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小明2号",
    "grade" : 1,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 3 */
    {
    "_id" : ObjectId("5a62e4deff7f0e1bec06ac49"),
    "grade" : 3,
    "name" : "小明2号",
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }
    after
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    /**接口返回数据**/
    {
    "res": "success",
    "data": {
    "birth": 1515585891367,
    "grade": 1,
    "id": "201801102003",
    "name": "小明2号"
    }
    //此时看到的数据时旧数据
    }
    /**mongo数据变动**/
    /* 1 */
    {
    "_id" : "1234567891",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小红",
    "grade" : 2,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 2 */
    {
    "_id" : "201801102003",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小明2号",
    "grade" : 2,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 3 */
    {
    "_id" : ObjectId("5a62e4deff7f0e1bec06ac49"),
    "grade" : 3,
    "name" : "小明2号",
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }
    findAndModify(Query query, Update update, FindAndModifyOptions options, Class entityClass, String collectionName)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
        @RequestMapping(value = "/updateMongoFunc13", method = RequestMethod.GET)
    @ApiOperation(notes = "findAndModify(Query query, Update update, FindAndModifyOptions options, Class<T> " +
    "entityClass, String collectionName)", value = "mongo修改13", produces = "application/json")
    public String updateMongoFunc13() {
    Update update = new Update();
    update.set("grade", 2);
    FindAndModifyOptions options = new FindAndModifyOptions();
    //默认false
    // options.returnNew(true); //是否返回更新后数据
    options.upsert(true); //是否更新(不存在则插入)
    // options.remove(true); //是否删除,为true时不会更新操作,如果returnNew为true则返回旧数据,并且删除
    Student andModify = mongoTemplate.findAndModify(Common.getQueryNormal(1, "小明2号"), update, options, Student
    .class, "student");
    return Common.successMsg(andModify);
    }
    执行结果:
    before
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    /* 1 */
    {
    "_id" : "1234567891",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小红",
    "grade" : 2,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 2 */
    {
    "_id" : "201801102003",
    "_class" : "com.janwarlen.entity.Student",
    "name" : "小明2号",
    "grade" : 2,
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }

    /* 3 */
    {
    "_id" : ObjectId("5a62e4deff7f0e1bec06ac49"),
    "grade" : 3,
    "name" : "小明2号",
    "birth" : ISODate("2018-01-10T12:04:51.367Z")
    }
    after
    1
    2
    3
    4
    5
    /**接口返回数据**/
    {
    "res": "success"
    }
    //意味着未找到需要修改数据

欢迎关注我的其它发布渠道