MongoCollection操作mongodb(增删改,高级查询,分页,排序)
摘要:
一. 配置: springboot 项目为例
二. 增加: insertOne insertMany
三. 删除 deleteOne deleteMany
四. 更新 updateOne updateMany
五. 查询(分页,排序,不等于,大于,小于,包含)
一. 配置mongo连接
springboot 项目为例
pom.xml
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver</artifactId>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-async</artifactId>
</dependency>
application.properties
## mongodb
spring.data.mongodb.database=
spring.data.mongodb.host=
spring.data.mongodb.password=
spring.data.mongodb.port=
spring.data.mongodb.username=
配置类
@Configuration
public class MongodbConfig {
@Value("${spring.data.mongodb.host}")
private String host;
@Value("${spring.data.mongodb.port}")
private int port;
@Value("${spring.data.mongodb.username}")
private String userName;
@Value("${spring.data.mongodb.database}")
private String mongoDatabase;
@Value("${spring.data.mongodb.password}")
private String password;
@Bean(name = "pojoCodecRegistry")
public CodecRegistry pojoCodecRegistry() {
return fromRegistries(MongoClient.getDefaultCodecRegistry(),
fromProviders(PojoCodecProvider.builder().automatic(true).build()));
}
@Bean(name = "mongoClient")
public MongoClient mongoClient(CodecRegistry pojoCodecRegistry) {
ServerAddress serverAddress = new ServerAddress(host, port);
MongoCredential credential = MongoCredential.createCredential(userName, mongoDatabase, password.toCharArray());
Builder builder = MongoClientOptions.builder();
builder.codecRegistry(pojoCodecRegistry);
return new MongoClient(serverAddress,credential,builder.build());
}
@Bean(name = "mongoDatabase")
public MongoDatabase mongoDatabase(MongoClient mongoClient, CodecRegistry pojoCodecRegistry) {
MongoDatabase database = mongoClient.getDatabase(mongoDatabase);
database = database.withCodecRegistry(pojoCodecRegistry);
return database;
}
}
```
#### 方便获取集合的抽象类(其他类继承这个抽象类)
```java
public abstract class BaseMongo {
protected Log log = LogFactory.getLog(this.getClass());
@Autowired
private MongoDatabase mongoDatabase;
protected abstract void debug(Object message);
/**
* get collection
*
* @param collectionName
* @return
*/
protected MongoCollection<Document> getCollection(String collectionName) {
return mongoDatabase.getCollection(collectionName);
}
/**
* get collection
*
* @param collectionName
* @param clazz
* @return
*/
protected <T> MongoCollection<T> getCollection(String collectionName, Class<T> clazz) {
return mongoDatabase.getCollection(collectionName, clazz);
}
}
二. 新增
可以直接操作实体类转jsonstr,进行操作
insertOne
insertMany
/**
* Inserts the provided document. If the document is missing an identifier, the driver should generate one.
*
* <p>Note: Supports retryable writes on MongoDB server versions 3.6 or higher when the retryWrites setting is enabled.</p>
* @param document the document to insert
* @throws com.mongodb.MongoWriteException if the write failed due some other failure specific to the insert command
* @throws com.mongodb.MongoWriteConcernException if the write failed due being unable to fulfil the write concern
* @throws com.mongodb.MongoException if the write failed due some other failure
*/
void insertOne(TDocument document);
/**
* Inserts one or more documents. A call to this method is equivalent to a call to the {@code bulkWrite} method
*
* <p>Note: Supports retryable writes on MongoDB server versions 3.6 or higher when the retryWrites setting is enabled.</p>
* @param documents the documents to insert
* @throws com.mongodb.MongoBulkWriteException if there's an exception in the bulk write operation
* @throws com.mongodb.MongoException if the write failed due some other failure
* @see com.mongodb.client.MongoCollection#bulkWrite
*/
void insertMany(List<? extends TDocument> documents);
示例代码
public class TestMongoImpl extends BaseMongo implements TestMongo {
@Override
public void saveMethod1(Map<String,Object> params) {
MongoCollection<Document> coll = this.getCollection("test_collection");
//单个学生数据添加
Document doc = new Document();
doc.append("stu_id",params.get(""));
doc.append("name",params.get(""));
doc.append("age",params.get(""));
coll.insertOne(doc);
//多个学生数据添加 模拟数据
List<Document> list = new ArrayList<>();
list.add(doc);
list.add(doc);
list.add(doc);
coll.insertMany(list);
}
@Override
public void saveMethod2(StudentEntity student) {
MongoCollection<Document> coll = this.getCollection("test_collection");
//单个学生添加
String s = JSONObject.toJSONString(student);
Document parse = Document.parse(s);
coll.insertOne(parse);
//或者
MongoCollection<StudentEntity> coll=this.getCollection("test_collection", StudentEntity.class);
coll.insertOne(student);
//多个同上
}
@Override
protected void debug(Object message) {
MongoCollection<Document> coll = this.getCollection("test_collection");
}
}
三. 删除
deleteOne
try {
this.getCollection("test_collection").deleteOne(new Document("uuid", uuid));
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("删除失败" + e.getMessage());
}
deleteMany ("$in")
try {
List<String> ids = xxxxx;
Document deleteWhere = new Document();
deleteWhere.put("uuid", new Document("$in", ids));
DeleteResult deleteResult = this.getCollection().deleteMany(deleteWhere);
} catch (RuntimeException ex) {
log.error("删除消息错误:" + ex.getMessage());
}
四. 更新
updateOne
try {
Document updateWhere = new Document();
updateWhere.put("uuid", "111");
this.getMessageCollection("test_collection").updateMany(updateWhere, set("status", status));
} catch (RuntimeException ex) {
log.error("修改消息状态错误:" + ex.getMessage());
}
updateMany
try {
List<String> ids = xxxxx;
Document updateWhere = new Document();
//筛选条件
updateWhere.put("uuid", new Document("$in", ids));
this.getCollection("test_collection").updateMany(updateWhere, set("status", status));
} catch (RuntimeException ex) {
log.error("修改消息状态错误:" + ex.getMessage());
}
五. 查询
排序 sort
分页 skip limit
上代码
int start = (int) params.get("start");
int limit = (int) params.get("limit");
Document filter = new Document();
filter.append("name","王大锤子");
FindIterable<Document> iterable = this.getCollection("ti").find(filter).skip(start)
.limit(limit).sort(new Document("age", -1));//-1 desc
大于 小于 大于等于 小于等于 不等于 包含
$gt $lt $gte $lte $ne $in
Document filter = new Document();
//不等于 18岁的
filter.append("age",new Document("$ne", 18));
//大于 18岁的
// filter.append("age",new Document("$gt", 18));
//小于 18岁的
// filter.append("age",new Document("$lt", 18));
FindIterable<Document> iterable = this.getCollection("ti").find(filter)
其他用法同上
结尾:
本文是最近学习mongodb的一些总结和记录,如有不对的地方,欢迎评论吐槽。