MongoDB十分钟搞定CRUD
程序员文章站
2022-07-10 12:11:10
...
转载:https://blog.csdn.net/soul_code/article/details/53585255
一、环境准备
MongoDB环境安装参照 MongoDBWindows平台安装
二、创建项目,添加MongoDB驱动依赖Jar
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.4.0</version>
</dependency>
三、创建连接
// To directly connect to a single MongoDB server
// (this will not auto-discover the primary even if it's a member of a replica set)
MongoClient mongoClient = new MongoClient();
// or
MongoClient mongoClient = new MongoClient( "localhost" );
// or
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
// or, to connect to a replica set, with auto-discovery of the primary, supply a seed list of members
MongoClient mongoClient = new MongoClient(
Arrays.asList(new ServerAddress("localhost", 27017),
new ServerAddress("localhost", 27018),
new ServerAddress("localhost", 27019)));
// or use a connection string
MongoClientURI connectionString = new MongoClientURI("mongodb://localhost:27017,localhost:27018,localhost:27019");
MongoClient mongoClient = new MongoClient(connectionString);
MongoDatabase database = mongoClient.getDatabase("mydb");
这是驱动api提供的几种连接数据库的方式,选一个自己喜欢的即可
四、开始CRUD
- insert
这里先插入一点点数据方便后面测试
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
MongoDatabase mongoDatabase = mongoClient.getDatabase("dbtest");
MongoCollection<Document> collection = mongoDatabase.getCollection("users");
for (int i = 0; i < 100000; i++) {
Document document= new Document();
document.append("name", "white"+i);
document.append("age",i);
document.append("sex",i%2);
document.append("money",i*10);
// insert into users(....)
collection.insertOne(document);
}
mongoClient.close();
- query
①条件查询
@Test
public void findByCondition(){
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
MongoDatabase db = mongoClient.getDatabase("dbtest");
MongoCollection<Document> collection = db.getCollection("users");
// select * from user
collection.find();
// select top 1 * from user where name = 'white11'
collection.find(Filters.eq("name", "white11")).first();
// select * from user where age < 10
collection.find(Filters.lt("age", 10));
// select * from user where age>= 70 and age<=100
collection.find(Filters.and(Filters.lte("age", 100),Filters.gte("age", 70)));
mongoClient.close();
}
②排序
@Test
public void findBySort(){
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
MongoDatabase db = mongoClient.getDatabase("dbtest");
MongoCollection<Document> collection = db.getCollection("users");
// select * from user where age>= 70 and age<=100 order by sex desc ,age desc
FindIterable<Document> sort = collection.find(Filters.and(Filters.lte("age", 100),Filters.gte("age", 70))).sort(Indexes.descending("sex","age")).projection(new Document().append("_id", 0));
for (Document document : sort) {
System.out.println(document);
}
mongoClient.close();
}
- update
@Test
public void update(){
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
MongoDatabase db = mongoClient.getDatabase("dbtest");
MongoCollection<Document> collection = db.getCollection("users");
// udpate users set name = '大神' where name = 'white11'
UpdateResult updateOne = collection.updateOne(Filters.eq("name", "white11"), new Document().append("$set",new Document("name", "大神")));
UpdateResult updateMany = collection.updateMany(Filters.lt("age", 10), new Document().append("$inc", new Document().append("age", -100)));
// 影响行数
System.out.println(updateMany.getModifiedCount());
mongoClient.close();
}
- delete
@Test
public void delete(){
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
MongoDatabase db = mongoClient.getDatabase("dbtest");
MongoCollection<Document> collection = db.getCollection("users");
// delete users where name = 'white10'
collection.deleteOne(Filters.eq("name", "white10"));
// delete users where age < 10
collection.deleteMany(Filters.lt("age", 10));
mongoClient.close();
}
另一篇 :当Spring遇见MongoDB,五分钟搞定CRUD
来源 : https://blog.csdn.net/soul_code/article/details/53608254
一、引入相关依赖
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.9.5.RELEASE</version>
</dependency>
</dependencies>
二、配置MongoDB连接
spring官网提供了很多种配置方式 spring-mongo-reference
这是其中一种
package me.sclove.admin.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.MongoClientFactoryBean;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import com.mongodb.Mongo;
@Configuration
public class MongoConfig {
@Bean
public MongoClientFactoryBean mongo(){
MongoClientFactoryBean factoryBean = new MongoClientFactoryBean();
factoryBean.setHost("localhost"); // 数据库地址
factoryBean.setPort(27017); // 端口
return factoryBean;
}
@Bean
public MongoOperations mongoTemplate(Mongo mongo){
// 操作Mongo的模板类,提供了非常纯粹的oo操作数据库的api
return new MongoTemplate(mongo, "dbtest"); // dbtest 为数据库名
}
}
三、编写测试类
①测试实体类
public class Person {
private String id;
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
②Test类
- insert
@Test
public void insert() {
AnnotationConfigApplicationContext a = new AnnotationConfigApplicationContext(
MongoConfig.class);
MongoOperations mongoOps = a.getBean(MongoOperations.class);
Person person = new Person("white", 23);
// 单条插入
mongoOps.insert(person);
List<Person> persons = new ArrayList<Person>();
for (int i = 1; i <= 20; i++) {
persons.add(new Person("white" + i + "号", 20 + i));
}
// 批量插入
mongoOps.insertAll(persons);
a.close();
}
一行代码搞定了Mongo的插入操作,这里我们并没有设置Mongo的集合名,只是传入了一个实体对象,初步猜想MongoOperations 模板类应该是把实体类的类名或者全类名作为了集合的名称,用一个Mongo GUI工具打开数据库
可以看到,基本印证了猜想,这里MongoOperations 把类名小写之后作为了Mongo集合的名称,而把当前类的全类名作为了一个字段存储到了数据库中
- query
为了方便操作
// 静态导入
import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Update.update;
@Test
public void query() {
AnnotationConfigApplicationContext a = new AnnotationConfigApplicationContext(
MongoConfig.class);
MongoOperations mongoOps = a.getBean(MongoOperations.class);
// 查询匹配条件的第一条数据
Person findOne = mongoOps.findOne(new Query(where("name").is("white")), Person.class);
System.out.println(findOne);
// 查询所有记录
List<Person> all = mongoOps.findAll(Person.class);
System.out.println(all);
// 查询age >= 25 and age < 30
Query query = new Query(where("age").gte(25).lt(30));
List<Person> findByCondition = mongoOps.find(query , Person.class);
System.out.println(findByCondition);
// 原生命令方式
BasicQuery bq =new BasicQuery("{name:'white'}");
Person findOne2 = mongoOps.findOne(bq, Person.class);
System.out.println(findOne2);
a.close();
}
- delete
@Test
public void delete() {
AnnotationConfigApplicationContext a = new AnnotationConfigApplicationContext(
MongoConfig.class);
MongoOperations mongoOps = a.getBean(MongoOperations.class);
// 删除age>=25的所有记录
WriteResult remove = mongoOps.remove(new Query(where("age").gte(25)),Person.class);
// 查出第一条匹配的记录并把这条记录删除 阅后即焚
Person findAndRemove = mongoOps.findAndRemove(new Query(where("name").is("white")), Person.class);
System.out.println(findAndRemove);
// 按对象删除
Person p = mongoOps.findOne(new Query(where("age").is(22)), Person.class);
mongoOps.remove(p);
// 删除集合
mongoOps.dropCollection(Person.class);
a.close();
}
- update
@Test
public void updateTest() {
AnnotationConfigApplicationContext a = new AnnotationConfigApplicationContext(
MongoConfig.class);
MongoOperations mongoOps = a.getBean(MongoOperations.class);
// 更新一条
mongoOps.updateFirst(new Query(where("age").is(23)), update("name","white小哥"), Person.class);
// 更新多条
mongoOps.updateMulti(new Query(where("age").lte(23)), update("name","white大哥"), Person.class);
a.close();
}
版权声明:
上一篇: django + OSQA,十分钟内搞定一个问答网站
下一篇: 真·十分钟搞定Flex布局