1、依赖包
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency>
2、配置
# MongoDB 单机 #spring.data.mongodb.uri=mongodb://lt_dms_test:1j23W1tLBZ21eoCZ@10.123.4.41:27001/dms_test # MongoDB 集群 spring.data.mongodb.uri=mongodb://lt_dms_test:1j23W1tLBZ21eoCZ@ops-mongodb-test01.shein.com:27001,ops-mongodb-test02.shein.com:27001,ops-mongodb-test03.shein.com:27001/dms_test
3、代码举例
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.gxr.dmsData.common.BaseTest; import lombok.extern.slf4j.Slf4j; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import java.time.LocalDateTime; import java.util.List; import java.util.Random; /** * @author :gongxr * @description:测试MongoDB操作 * @date :Created in 2021/10/12 */ @Slf4j public class TestMongoDB extends BaseTest { @Autowired MongoTemplate mongoTemplate; final String collection = "dms_rt_sales_volume_log_202006"; final String collection2 = "mongo_test"; /** * 查询单个记录 */ @Test public void testFindOne() { Query query = new Query(Criteria.where("skc").is("RDRE170712102")); // Query query = new Query(Criteria.where("skc").is("RDRE170712102").and("name").is("Tom")); JSONObject result = mongoTemplate.findOne(query, JSONObject.class, collection); log.info("返回结果:【{}】", result.toJSONString()); } /** * 查询多个记录 */ @Test public void testFind() { Query query = new Query(Criteria.where("addUid").is("admin")); List<JSONObject> result = mongoTemplate.find(query, JSONObject.class, collection); log.info("返回结果:【{}】", JSON.toJSONString(result)); } /** * 插入数据 */ @Test public void testInsert() { if (!mongoTemplate.collectionExists(collection2)) { mongoTemplate.createCollection(collection2); } JSONObject object = new JSONObject(); object.put("name", "Tom"); object.put("age", new Random().nextInt(100)); object.put("job", "老师"); object.put("date", LocalDateTime.now()); mongoTemplate.insert(object, collection2); } /** * 删除数据 */ @Test public void testDelete() { Query query = new Query(Criteria.where("age").is(4)); mongoTemplate.remove(query, collection2); } /** * 创建与删除Collection */ @Test public void testCollection() { // 创建Collection if (!mongoTemplate.collectionExists(collection2)) { mongoTemplate.createCollection(collection2); } // 删除Collection mongoTemplate.dropCollection(collection2); } }
参考链接:https://spring.hhui.top/spring-blog/2019/01/13/190113-SpringBoot%E9%AB%98%E7%BA%A7%E7%AF%87MongoDB%E4%B9%8B%E6%9F%A5%E8%AF%A2%E5%9F%BA%E6%9C%AC%E4%BD%BF%E7%94%A8%E5%A7%BF%E5%8A%BF/