前言:空余时间研究下MongoDB,它作为典型的NoSQL数据库,存储JSON格式的数据十分方便,本文将会记录安装和使用的部分方法。
一. 安装与配置
安装过程略,配置远程访问:
1)先配置管理员用户
1 2 3
| > use admin switched to db admin > db.createUser({user:"admin",pwd:"admin",roles:[{role:"root", db:"admin"}]})
|
2)配置文件修改
1 2 3 4 5
| net: port: 27017 bindIp: 0.0.0.0 security: authorization: enabled
|
二. 在SpringBoot中使用
配置
1)pom.xml中添加依赖
1 2 3 4
| <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency>
|
2)配置application.yml
1 2 3 4 5 6 7 8 9
| spring: data: mongodb: authentication-database: admin database: test username: admin password: admin123456 host: 127.0.0.1 port: 27017
|
映射
只需要在对应实体类上加注解:
1
| @Document(collection = "user")
|
自定义id
插入记录时,MongoDB会自动生成一条不重复的_id字段,若想自定义,可以通过@MongoId注解
1 2
| @MongoId private String title;
|
使用
1)直接存储 JSONObject
1 2 3 4 5 6
| @Autowired private MongoTemplate mongoTemplate;
public void test(){ mongoTemplate.save(JSONObject对象, 集合名); }
|
使用MongoRepository进行CRUD
略
使用MongoTemplate进行CRUD
https://blog.csdn.net/liboyang71/article/details/87916549
三. 原生操作
权限操作
1 2 3 4 5 6 7 8
| use admin
db.system.users.find()
db.system.users.remove({})
db.createUser({user:"root",pwd:"test123",roles:[{role:"root", db:"admin"}]})
|
原生查询
1 2 3 4 5
| db.getCollection("CET4_2").find({"content.word.wordId":"CET4_2_1"}).pretty()
db.getCollection('CET4_2').distinct("content.word.wordId").length
|
未完待续