原文链接:http://www.mkyong.com/mongodb/spring-data-mongodb-update-document/
In Spring data – MongoDB, you can use following methods to update documents.
- save – Update the whole object, if “_id” is present, perform an update, else insert it.
- updateFirst – Updates the first document that matches the query.
- updateMulti – Updates all documents that match the query.
- Upserting – If no document that matches the query, a new document is created by combining the query and update object.
- findAndModify – Same with updateMulti, but it has an extra option to return either the old or newly updated document.
P.S All examples are tested under mongo-java-driver-2.11.0.jar
and spring-data-mongodb-1.2.0.RELEASE.jar
1. saveOrUpdate – part 1 example
// Assume below json data is inserted into MongoDB. { "_id" : ObjectId("id"), "ic" : "1001", "name" : "appleA", "age" : 20, "createdDate" : ISODate("2013-04-06T23:17:35.530Z") } // Find the document, modify and update it with save() method. Query query = new Query(); query.addCriteria(Criteria.where("name").is("appleA")); User userTest1 = mongoOperation.findOne(query, User.class); System.out.println("userTest1 - " + userTest1); //modify and update with save() userTest1.setAge(99); mongoOperation.save(userTest1); //get the updated object again User userTest1_1 = mongoOperation.findOne(query, User.class); System.out.println("userTest1_1 - " + userTest1_1); //Output userTest1 - User [id=id, ic=1001, name=appleA, age=20, createdDate=Sat Apr 06 23:17:35 MYT 2013] userTest1_1 - User [id=id, ic=1001, name=appleA, age=99, createdDate=Sat Apr 06 23:17:35 MYT 2013]
2. saveOrUpdate – part 2 example
This is a failed example, read carefully, a really common mistake.
Assume below json data is inserted into MongoDB.
{
"_id" : ObjectId("id"),
"ic" : "1002",
"name" : "appleB",
"age" : 20,
"createdDate" : ISODate("2013-04-06T15:22:34.530Z")
}
In Query
, you get the document returned with a single “name” field value only, it did happened often to save the object returned size. The returned “User” object has null value in the fields : age, ic and createdDate, if you modify the ‘age’ field and update it, it will override everything instead of update the modified field – ‘age’.
Query query = new Query();
query.addCriteria(Criteria.where("name").is("appleB"));
query.fields().include("name");
User userTest2 = mongoOperation.findOne(query, User.class);
System.out.println("userTest2 - " + userTest2);
userTest2.setAge(99);
mongoOperation.save(userTest2);
// ooppss, you just override everything, it caused ic=null and
// createdDate=null
Query query1 = new Query();
query1.addCriteria(Criteria.where("name").is("appleB"));
User userTest2_1 = mongoOperation.findOne(query1, User.class);
System.out.println("userTest2_1 - " + userTest2_1);
Output
userTest2 - User [id=51603dba3004d7fffc202391, ic=null, name=appleB, age=0, createdDate=null] userTest2_1 - User [id=51603dba3004d7fffc202391, ic=null, name=appleB, age=99, createdDate=null]
After the save(), the field ‘age’ is updated correctly, but ic and createdDate are both set to null, the entire “user” object is updated. To update a single field / key value, don’t use save(), use updateFirst() or updateMulti() instead.
3. updateFirst example
Updates the first document that matches the query. In this case, only the single field “age” is updated.
{
"_id" : ObjectId("id"),
"ic" : "1003",
"name" : "appleC",
"age" : 20,
"createdDate" : ISODate("2013-04-06T23:22:34.530Z")
}
//returns only 'name' field
Query query = new Query();
query.addCriteria(Criteria.where("name").is("appleC"));
query.fields().include("name");
User userTest3 = mongoOperation.findOne(query, User.class);
System.out.println("userTest3 - " + userTest3);
Update update = new Update();
update.set("age", 100);
mongoOperation.updateFirst(query, update, User.class);
//returns everything
Query query1 = new Query();
query1.addCriteria(Criteria.where("name").is("appleC"));
User userTest3_1 = mongoOperation.findOne(query1, User.class);
System.out.println("userTest3_1 - " + userTest3_1);
Output
userTest3 - User [id=id, ic=null, name=appleC, age=0,
createdDate=null]
userTest3_1 - User [id=id, ic=1003, name=appleC, age=100,
createdDate=Sat Apr 06 23:22:34 MYT 2013]
4. updateMulti example
Updates all documents that matches the query.
{
"_id" : ObjectId("id"),
"ic" : "1004",
"name" : "appleD",
"age" : 20,
"createdDate" : ISODate("2013-04-06T15:22:34.530Z")
}
{
"_id" : ObjectId("id"),
"ic" : "1005",
"name" : "appleE",
"age" : 20,
"createdDate" : ISODate("2013-04-06T15:22:34.530Z")
}
//show the use of $or operator
Query query = new Query();
query.addCriteria(Criteria
.where("name").exists(true)
.orOperator(Criteria.where("name").is("appleD"),
Criteria.where("name").is("appleE")));
Update update = new Update();
//update age to 11
update.set("age", 11);
//remove the createdDate field
update.unset("createdDate");
// if use updateFirst, it will update 1004 only.
// mongoOperation.updateFirst(query4, update4, User.class);
// update all matched, both 1004 and 1005
mongoOperation.updateMulti(query, update, User.class);
System.out.println(query.toString());
List<User> usersTest4 = mongoOperation.find(query4, User.class);
for (User userTest4 : usersTest4) {
System.out.println("userTest4 - " + userTest4);
}
Output
Query: { "name" : { "$exists" : true} , "$or" : [ { "name" : "appleD"} , { "name" : "appleE"}]}, Fields: null, Sort: null userTest4 - User [id=id, ic=1004, name=appleD, age=11, createdDate=null] userTest4 - User [id=id, ic=1005, name=appleE, age=11, createdDate=null]
5. Upsert example
If document is matched, update it, else create a new document by combining the query and update object, it’s works like findAndModifyElseCreate()
{
//no data
}
//search a document that doesn't exist
Query query = new Query();
query.addCriteria(Criteria.where("name").is("appleZ"));
Update update = new Update();
update.set("age", 21);
mongoOperation.upsert(query, update, User.class);
User userTest5 = mongoOperation.findOne(query, User.class);
System.out.println("userTest5 - " + userTest5);
Output, a new document is created by combining both query and update object.
serTest5 - User [id=id, ic=null, name=appleZ, age=21, createdDate=null]
6. findAndModify example
Find and modify and get the newly updated object from a single operation.
{
"_id" : ObjectId("id"),
"ic" : "1006",
"name" : "appleF",
"age" : 20,
"createdDate" : ISODate("2013-04-07T13:11:34.530Z")
}
Query query6 = new Query();
query6.addCriteria(Criteria.where("name").is("appleF"));
Update update6 = new Update();
update6.set("age", 101);
update6.set("ic", 1111);
//FindAndModifyOptions().returnNew(true) = newly updated document
//FindAndModifyOptions().returnNew(false) = old document (not update yet)
User userTest6 = mongoOperation.findAndModify(
query6, update6,
new FindAndModifyOptions().returnNew(true), User.class);
System.out.println("userTest6 - " + userTest6);
Output
userTest6 - User [id=id, ic=1111, name=appleF, age=101, createdDate=Sun Apr 07 13:11:34 MYT 2013]
7. Full example
Full application to combine everything from example 1 to 6.
package com.mkyong.core;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import com.mkyong.config.SpringMongoConfig;
import com.mkyong.model.User;
public class UpdateApp {
public static void main(String[] args) {
// For Annotation
ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringMongoConfig.class);
MongoOperations mongoOperation = (MongoOperations) ctx.getBean("mongoTemplate");
// insert 6 users for testing
List<User> users = new ArrayList<User>();
User user1 = new User("1001", "appleA", 20, new Date());
User user2 = new User("1002", "appleB", 20, new Date());
User user3 = new User("1003", "appleC", 20, new Date());
User user4 = new User("1004", "appleD", 20, new Date());
User user5 = new User("1005", "appleE", 20, new Date());
User user6 = new User("1006", "appleF", 20, new Date());
uses.add(user1);
uses.add(user2);
uses.add(user3);
uses.add(user4);
uses.add(user5);
uses.add(user6);
monoOperation.insert(users, User.class);
// ase 1 ... find and update
Sysem.out.println("Case 1");
Quey query1 = new Query();
quey1.addCriteria(Criteria.where("name").is("appleA"));
Use userTest1 = mongoOperation.findOne(query1, User.class);
Sysem.out.println("userTest1 - " + userTest1);
useTest1.setAge(99);
monoOperation.save(userTest1);
Use userTest1_1 = mongoOperation.findOne(query1, User.class);
Sysem.out.println("userTest1_1 - " + userTest1_1);
// ase 2 ... select single field only
Sysem.out.println("\nCase 2");
Quey query2 = new Query();
quey2.addCriteria(Criteria.where("name").is("appleB"));
quey2.fields().include("name");
Use userTest2 = mongoOperation.findOne(query2, User.class);
Sysem.out.println("userTest2 - " + userTest2);
useTest2.setAge(99);
monoOperation.save(userTest2);
// oppss, you just override everything, it caused ic=null an
// reatedDate=null
Quey query2_1 = new Query();
quey2_1.addCriteria(Criteria.where("name").is("appleB"));
Use userTest2_1 = mongoOperation.findOne(query2_1, User.class);
Sysem.out.println("userTest2_1 - " + userTest2_1);
Sysem.out.println("\nCase 3");
Quey query3 = new Query();
quey3.addCriteria(Criteria.where("name").is("appleC"));
quey3.fields().include("name");
Use userTest3 = mongoOperation.findOne(query3, User.class);
Sysem.out.println("userTest3 - " + userTest3);
Updte update3 = new Update();
updte3.set("age", 100);
monoOperation.updateFirst(query3, update3, User.class);
Quey query3_1 = new Query();
quey3_1.addCriteria(Criteria.where("name").is("appleC"));
Use userTest3_1 = mongoOperation.findOne(query3_1, User.class);
Sysem.out.println("userTest3_1 - " + userTest3_1);
Sysem.out.println("\nCase 4");
Quey query4 = new Query();
quey4.addCriteria(Criteria
.where("name")
.exists(true)
.orOperator(Criteria.where("name").is("appleD"),
Criteria.where("name").is("appleE")));
Updte update4 = new Update();
updte4.set("age", 11);
updte4.unset("createdDate");
// pdate 1004 only.
// ongoOperation.updateFirst(query4, update4, User.class);
// pdate all matched
monoOperation.updateMulti(query4, update4, User.class);
Sysem.out.println(query4.toString());
Lis<User> usersTest4 = mongoOperation.find(query4, User.class);
for(User userTest4 : usersTest4) {
System.out.println("userTest4 - " + userTest4);
}
Sysem.out.println("\nCase 5");
Quey query5 = new Query();
quey5.addCriteria(Criteria.where("name").is("appleZ"));
Updte update5 = new Update();
updte5.set("age", 21);
monoOperation.upsert(query5, update5, User.class);
Use userTest5 = mongoOperation.findOne(query5, User.class);
Sysem.out.println("userTest5 - " + userTest5);
Sysem.out.println("\nCase 6");
Quey query6 = new Query();
quey6.addCriteria(Criteria.where("name").is("appleF"));
Updte update6 = new Update();
updte6.set("age", 101);
updte6.set("ic", 1111);
Use userTest6 = mongoOperation.findAndModify(query6, update6,
new FindAndModifyOptions().returnNew(true), User.class);
Sysem.out.println("userTest6 - " + userTest6);
monoOperation.dropCollection(User.class);
}
}
Output
Case 1 userTest1 - User [id=id, ic=1001, name=appleA, age=20, createdDate=Sun Apr 07 13:22:48 MYT 2013] userTest1_1 - User [id=id, ic=1001, name=appleA, age=99, createdDate=Sun Apr 07 13:22:48 MYT 2013] Case 2 userTest2 - User [id=id, ic=null, name=appleB, age=0, createdDate=null] userTest2_1 - User [id=id, ic=null, name=appleB, age=99, createdDate=null] Case 3 userTest3 - User [id=id, ic=null, name=appleC, age=0, createdDate=null] userTest3_1 - User [id=id, ic=1003, name=appleC, age=100, createdDate=Sun Apr 07 13:22:48 MYT 2013] Case 4 Query: { "name" : { "$exists" : true} , "$or" : [ { "name" : "appleD"} , { "name" : "appleE"}]}, Fields: null, Sort: null userTest4 - User [id=id, ic=1004, name=appleD, age=11, createdDate=null] userTest4 - User [id=id, ic=1005, name=appleE, age=11, createdDate=null] Case 5 userTest5 - User [id=id, ic=null, name=appleZ, age=21, createdDate=null] Case 6 userTest6 - User [id=id, ic=1006, name=appleF, age=20, createdDate=Sun Apr 07 13:22:48 MYT 2013]
相关推荐
Spring Data MongoDB是一个强大的Java库,它为开发人员提供了一种简单的方式来访问和操作MongoDB数据库。这个库是Spring Data框架的一部分,旨在简化数据访问层的实现,尤其在使用NoSQL数据库如MongoDB时。MongoDB...
3. **Document和MongoEntity**:在Spring MongoDB中,数据模型通常表示为`org.springframework.data.mongodb.core.mapping.Document`注解的类。这个注解告诉Spring如何将类映射到MongoDB的集合中。`@Id`注解用于指定...
System.out.println("Full Document: " + fullDocument.toJson()); }); } } ``` 在这个例子中,我们创建了一个Change Stream,监听`mycollection`集合,并在有变更事件发生时处理它们。你可以根据实际需求,将...
接下来,我们将使用Spring Data for MongoDB创建一个具备基本CRUD(Create, Read, Update, Delete)功能的Java应用——NatureStore。 1. **添加依赖库**:确保项目的lib目录包含了Spring Data for MongoDB所需的jar...
SpringData MongoDB提供了`Aggregation`类,可以构建聚合管道。例如,以下代码示例统计用户按年龄分组的数量: ```java import org.springframework.data.mongodb.core.aggregation.*; Aggregation aggregation = ...
如果你的应用是基于Spring框架的,可以使用Spring Data MongoDB简化操作。只需在配置文件中声明MongoDB的相关设置,并创建Repository接口,即可实现CRUD操作。 8. **事务处理 (Transactions)** 自MongoDB 4.0开始...
在MongoDB与Java对象之间进行数据转换时,通常使用MongoDB的Java驱动程序中的Document类或Spring Data的MongoEntity或MongoDBObject。MongoDB的Document类可以直接映射到Java的Map对象,而Spring Data提供了...
在SpringBoot框架中,通过Spring Data MongoDB模块,我们可以轻松地与MongoDB进行交互,极大地简化了开发流程。 首先,我们来详细了解如何在SpringBoot项目中配置MongoDB。在`application.properties`或`...
在这个“MongoDb增删改查的网站范例”中,我们将探讨如何利用Spring Data项目和MongoDB适配器进行数据库操作。 Spring Data是一个强大的框架,它简化了与各种数据存储系统的交互,包括MongoDB。Spring Data MongoDB...
8. **Spring框架集成**:若使用Spring框架,可以借助Spring Data MongoDB模块简化MongoDB的集成,提供更高级别的抽象和便利性。 通过以上知识点,我们可以构建一个JSP应用程序,实现与MongoDB的交互,展示和处理...
- **Spring Data MongoDB**: Spring提供的一套库,简化了MongoDB在Java应用中的使用。 - **MongoTemplate**: Spring Data MongoDB的核心组件,提供了对数据库操作的模板方法。 - **Repository接口**: 可以定义...
在Spring框架中,我们可以利用Spring Data MongoDB模块来简化MongoDB的操作。这个模块提供了Repository抽象,允许开发者通过接口定义数据操作,而无需编写繁琐的DAO层代码。例如,我们可以定义一个`MongoRepository`...
为了更改连接设置,可以在 `application.properties` 中配置 `spring.data.mongodb.host` 和 `spring.data.mongodb.port` 属性,例如: ``` spring.data.mongodb.host=mongoserver spring.data.mongodb.port=27017 ...
SpringData MongoDB提供了简便的方法来执行这些操作,如`save()`, `findAll()`, `findById()`, `update()`和`delete()`等。 - 数据模型:定义Java对象作为MongoDB文档的映射,使用`@Document`注解标记类,使用`@Id`...
import org.springframework.data.mongodb.core.mapping.Document; @Document(collection = "users") public class User { @Id private String id; private String name; private String email; // getters ...
这些方法可能接受自定义的Java对象(通常称为Document对象),这些对象对应于MongoDB的文档结构,并通过Spring Data自动转换为BSON格式存储在MongoDB中。 `index.jsp`文件是JSP(JavaServer Pages)文件,通常用于...
- 配置:在`application.properties`或`application.yml`中设置MongoDB连接信息,如`spring.data.mongodb.uri`。 - 使用`@EnableMongoRepositories`注解开启MongoDB的仓储支持。 - 创建MongoRepository接口,...
通过对MongoDB的基础配置、CRUD操作、索引管理以及如何使用Spring Data MongoDB进行开发的学习,可以快速地将MongoDB应用于实际项目中,提高开发效率和系统的性能表现。希望这份快速上手指南能够帮助读者更好地理解...
本项目"MongoDB测试javaweb项目demo"应该包含了以上所述的MongoDB与Java Web集成的关键步骤,包括连接配置、数据操作以及可能的Spring Data MongoDB使用。通过深入研究这个项目,开发者可以学习到如何在实际项目中...