1.配置pom
pom.xml 直接提示 选择最低下的 Edit Starters...
2.模糊搜索mongo 选中选择框
pom 就会自动新增
3.SpringBoot 配置
spring:
data:
mongodb:
uri: mongodb://用户:密码@url:端口/db
#例如:uri: mongodb://root:123456@localhost:27017/db_test
在你需要的地方加入
/** 由springboot自动注入,默认配置会产生mongoTemplate这个bean */
@Autowired
private MongoTemplate mongoTemplate;
新增一条数据
JSONObject jsonObject = new JSONObject();
jsonObject.put("a", "1");
mongoTemplate.insert(jsonObject, "collectionName");
// insert('json','集合名称- 也可以没有')
更具'name'查询数据并返回
Query query = new Query(Criteria.where("name").is("帅旭旭"));
JSONObject redisInfo = mongoTemplate.findOne(query, JSONObject.class,"collectionName");
// JSONObject.class 可换成自己定义的类