mongoDB中文文档:https://docs.mongoing.com/
mongoDB官方文档:https://docs.mongodb.com/v5.0/
docker 安装 MongoDB
学习一个工具的时候不应该在安装上花费太多时间,所以采用docker安装
docker pull mongo
# --auth:需要密码才能访问容器服务。
docker run -itd --name mongo -p 27017:27017 mongo --auth
# 进入容器
docker exec -it mongo mongo admin
# 创建一个名为 admin,密码为 123456 的用户。
> db.createUser({ user:'admin',pwd:'123456',roles:[ { role:'userAdminAnyDatabase', db: 'admin'},"readWriteAnyDatabase"]});
# 尝试使用上面创建的用户信息进行连接。
> db.auth('admin', '123456')
简单使用
查看版本
> db.version()
5.0.5
查看/创建数据库
# use 命令切换数据库,当数据库不存在时会新建数据库,所以可以切换到不存在的数据库
> use myDB
switched to db myDB
> use myDB2
switched to db myDB2
# 查看当前所在数据库
> db
myDB2
# 展示所有数据库
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
>
查看/创建集合
MongoDB将文档存储在集合中。集合类似于关系数据库中的表。
# 如果不存在集合,则在您第一次为该集合存储数据/创建索引时,MongoDB会创建该集合
> db.myCollection.insertOne({x:1})
{
"acknowledged" : true,
"insertedId" : ObjectId("61d52c33875bb4c2408d6e53")
}
> db.myCollection2.createIndex({x:1})
{
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"createdCollectionAutomatically" : true,
"ok" : 1
}
# 查看该库下所有集合
> show collections
myCollection
myCollection2
简单crud
插入文档
db.collection.insertOne() 将单个文档插入到集合中
db.collection.insertMany() 将多个文件插入集合中。
db.collection.insert() 将单个文档或多个文档插入到集合中。
> db.myCollection.insertOne({x:1})
{
"acknowledged" : true,
"insertedId" : ObjectId("61d58543875bb4c2408d6e54")
}
> db.myCollection.insertMany([{name:"alix",age:15},{name:"jenson",age:18}])
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("61d585e4875bb4c2408d6e55"),
ObjectId("61d585e4875bb4c2408d6e56")
]
}
> db.myCollection.insert({name:"angila",age:15})
WriteResult({ "nInserted" : 1 })
> db.myCollection.insert([{name:"blus",age:15},{name:"zhangSang",age:18}])
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 2,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
查询文档
- db.collection.find( {} )
检索集合中的所有文档 db.collection.find( {} )
> db.myCollection.find( {} )
{ "_id" : ObjectId("61d52c33875bb4c2408d6e53"), "x" : 1 }
{ "_id" : ObjectId("61d58543875bb4c2408d6e54"), "x" : 1 }
{ "_id" : ObjectId("61d585e4875bb4c2408d6e55"), "name" : "alix", "age" : 15 }
{ "_id" : ObjectId("61d585e4875bb4c2408d6e56"), "name" : "jenson", "age" : 18 }
{ "_id" : ObjectId("61d58605875bb4c2408d6e57"), "name" : "angila", "age" : 15 }
{ "_id" : ObjectId("61d58620875bb4c2408d6e58"), "name" : "blus", "age" : 15 }
{ "_id" : ObjectId("61d58620875bb4c2408d6e59"), "name" : "zhangSang", "age" : 18 }
从查询结果可以看出,如果文档未指定_id字段,则MongoDB将具有ObjectId值的_id字段添加到新文档中
重新尝试一下插入,此时加入_id
,结果如下
# 插入一条已有_id的数据,报错`E11000 duplicate key`
> db.myCollection.insertOne({_id:ObjectId("61d52c33875bb4c2408d6e53"),x:1})
WriteError({
"index" : 0,
"code" : 11000,
"errmsg" : "E11000 duplicate key error collection: myDB.myCollection index: _id_ dup key: { _id: ObjectId('61d52c33875bb4c2408d6e53') }",
"op" : {
"_id" : ObjectId("61d52c33875bb4c2408d6e53"),
"x" : 1
}
}) :
WriteError({
"index" : 0,
"code" : 11000,
"errmsg" : "E11000 duplicate key error collection: myDB.myCollection index: _id_ dup key: { _id: ObjectId('61d52c33875bb4c2408d6e53') }",
"op" : {
"_id" : ObjectId("61d52c33875bb4c2408d6e53"),
"x" : 1
}
})
WriteError@src/mongo/shell/bulk_api.js:465:48
mergeBatchResults@src/mongo/shell/bulk_api.js:871:49
executeBatch@src/mongo/shell/bulk_api.js:940:13
Bulk/this.execute@src/mongo/shell/bulk_api.js:1182:21
DBCollection.prototype.insertOne@src/mongo/shell/crud_api.js:264:9
@(shell):1:1
# 指定_id不同就可以插入
> db.myCollection.insertOne({_id:ObjectId("61d52c33875bb4c2408d6e60"),x:1})
{
"acknowledged" : true,
"insertedId" : ObjectId("61d52c33875bb4c2408d6e60")
}
>
# 等值查询
> db.myCollection.find( {x:1} )
{ "_id" : ObjectId("61d52c33875bb4c2408d6e53"), "x" : 1 }
{ "_id" : ObjectId("61d58543875bb4c2408d6e54"), "x" : 1 }
{ "_id" : ObjectId("61d52c33875bb4c2408d6e60"), "x" : 1 }
>
- db.collection.find({ <field1>: <value1>, ... })
等值查询
> db.myCollection.find( {name:"alix",age:15} )
{ "_id" : ObjectId("61d585e4875bb4c2408d6e55"), "name" : "alix", "age" : 15 }
- db.collection.find({ <field1>: { <operator1>: <value1> }, ... })
等值查询单一字段多值
> db.myCollection.find( {name:"alix",age:{$in:[15,18]}} )
{ "_id" : ObjectId("61d585e4875bb4c2408d6e55"), "name" : "alix", "age" : 15 }
>
>
> db.myCollection.find( {age:{$in:[15,18]}} )
{ "_id" : ObjectId("61d585e4875bb4c2408d6e55"), "name" : "alix", "age" : 15 }
{ "_id" : ObjectId("61d585e4875bb4c2408d6e56"), "name" : "jenson", "age" : 18 }
{ "_id" : ObjectId("61d58605875bb4c2408d6e57"), "name" : "angila", "age" : 15 }
{ "_id" : ObjectId("61d58620875bb4c2408d6e58"), "name" : "blus", "age" : 15 }
{ "_id" : ObjectId("61d58620875bb4c2408d6e59"), "name" : "zhangSang", "age" : 18 }
查询语句中$in
就是查询操作符,更多查询操作符参考官方文档:https://docs.mongodb.com/manual/reference/operator/query/
更新文档
db.collection.updateOne(<filter>,<update>,<options>)
db.collection.updateMany(<filter>,<update>,<options>)
db.collection.replaceOne(<filter>,<update>,<options>)
和查询一样,<options>
就是提供的更新操作符,更多操作法参考官方文档:https://docs.mongodb.com/manual/reference/operator/update/
- updateOne
真就只更新一个
> db.myCollection.find( {} )
{ "_id" : ObjectId("61d52c33875bb4c2408d6e53"), "x" : 1 }
{ "_id" : ObjectId("61d58543875bb4c2408d6e54"), "x" : 1 }
{ "_id" : ObjectId("61d585e4875bb4c2408d6e55"), "name" : "alix", "age" : 15 }
{ "_id" : ObjectId("61d585e4875bb4c2408d6e56"), "name" : "jenson", "age" : 18 }
{ "_id" : ObjectId("61d58605875bb4c2408d6e57"), "name" : "angila", "age" : 15 }
{ "_id" : ObjectId("61d58620875bb4c2408d6e58"), "name" : "blus", "age" : 15 }
{ "_id" : ObjectId("61d58620875bb4c2408d6e59"), "name" : "zhangSang", "age" : 18 }
{ "_id" : ObjectId("61d52c33875bb4c2408d6e60"), "x" : 1 }
>
>
> db.myCollection.updateOne({x:1},{$set:{teacher:"gaoSeng",class:"三年二班"},$currentDate:{lastModified:true}})
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
>
>
> db.myCollection.find( {} )
{ "_id" : ObjectId("61d52c33875bb4c2408d6e53"), "x" : 1, "class" : "三年二班", "lastModified" : ISODate("2022-01-05T12:34:32.990Z"), "teacher" : "gaoSeng" }
{ "_id" : ObjectId("61d58543875bb4c2408d6e54"), "x" : 1 }
{ "_id" : ObjectId("61d585e4875bb4c2408d6e55"), "name" : "alix", "age" : 15 }
{ "_id" : ObjectId("61d585e4875bb4c2408d6e56"), "name" : "jenson", "age" : 18 }
{ "_id" : ObjectId("61d58605875bb4c2408d6e57"), "name" : "angila", "age" : 15 }
{ "_id" : ObjectId("61d58620875bb4c2408d6e58"), "name" : "blus", "age" : 15 }
{ "_id" : ObjectId("61d58620875bb4c2408d6e59"), "name" : "zhangSang", "age" : 18 }
{ "_id" : ObjectId("61d52c33875bb4c2408d6e60"), "x" : 1 }
>
- updateMany
> db.myCollection.find( {} )
{ "_id" : ObjectId("61d52c33875bb4c2408d6e53"), "x" : 1, "class" : "三年二班", "lastModified" : ISODate("2022-01-05T12:34:32.990Z"), "teacher" : "gaoSeng" }
{ "_id" : ObjectId("61d58543875bb4c2408d6e54"), "x" : 1 }
{ "_id" : ObjectId("61d585e4875bb4c2408d6e55"), "name" : "alix", "age" : 15 }
{ "_id" : ObjectId("61d585e4875bb4c2408d6e56"), "name" : "jenson", "age" : 18 }
{ "_id" : ObjectId("61d58605875bb4c2408d6e57"), "name" : "angila", "age" : 15 }
{ "_id" : ObjectId("61d58620875bb4c2408d6e58"), "name" : "blus", "age" : 15 }
{ "_id" : ObjectId("61d58620875bb4c2408d6e59"), "name" : "zhangSang", "age" : 18 }
{ "_id" : ObjectId("61d52c33875bb4c2408d6e60"), "x" : 1 }
>
>
> db.myCollection.updateMany({x:1},{$set:{teacher:"gaoSeng",class:"三年二班"},$currentDate:{lastModified:true}})
{ "acknowledged" : true, "matchedCount" : 3, "modifiedCount" : 3 }
>
>
> db.myCollection.updateMany({name:"alix"},{$set:{age:30},$currentDate:{lastModified:true}})
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
>
>
> db.myCollection.find( {} )
{ "_id" : ObjectId("61d52c33875bb4c2408d6e53"), "x" : 1, "class" : "三年二班", "lastModified" : ISODate("2022-01-05T12:36:17.008Z"), "teacher" : "gaoSeng" }
{ "_id" : ObjectId("61d58543875bb4c2408d6e54"), "x" : 1, "class" : "三年二班", "lastModified" : ISODate("2022-01-05T12:36:17.008Z"), "teacher" : "gaoSeng" }
{ "_id" : ObjectId("61d585e4875bb4c2408d6e55"), "name" : "alix", "age" : 30, "lastModified" : ISODate("2022-01-05T12:38:54.530Z") }
{ "_id" : ObjectId("61d585e4875bb4c2408d6e56"), "name" : "jenson", "age" : 18 }
{ "_id" : ObjectId("61d58605875bb4c2408d6e57"), "name" : "angila", "age" : 15 }
{ "_id" : ObjectId("61d58620875bb4c2408d6e58"), "name" : "blus", "age" : 15 }
{ "_id" : ObjectId("61d58620875bb4c2408d6e59"), "name" : "zhangSang", "age" : 18 }
{ "_id" : ObjectId("61d52c33875bb4c2408d6e60"), "x" : 1, "class" : "三年二班", "lastModified" : ISODate("2022-01-05T12:36:17.008Z"), "teacher" : "gaoSeng" }
>
- replaceOne 替换文档
> db.myCollection.find( {} )
{ "_id" : ObjectId("61d52c33875bb4c2408d6e53"), "x" : 1, "class" : "三年二班", "lastModified" : ISODate("2022-01-05T12:36:17.008Z"), "teacher" : "gaoSeng" }
{ "_id" : ObjectId("61d58543875bb4c2408d6e54"), "x" : 1, "class" : "三年二班", "lastModified" : ISODate("2022-01-05T12:36:17.008Z"), "teacher" : "gaoSeng" }
{ "_id" : ObjectId("61d585e4875bb4c2408d6e55"), "name" : "alix", "age" : 30, "lastModified" : ISODate("2022-01-05T12:38:54.530Z") }
{ "_id" : ObjectId("61d585e4875bb4c2408d6e56"), "name" : "jenson", "age" : 18 }
{ "_id" : ObjectId("61d58605875bb4c2408d6e57"), "name" : "angila", "age" : 15 }
{ "_id" : ObjectId("61d58620875bb4c2408d6e58"), "name" : "blus", "age" : 15 }
{ "_id" : ObjectId("61d58620875bb4c2408d6e59"), "name" : "zhangSang", "age" : 18 }
{ "_id" : ObjectId("61d52c33875bb4c2408d6e60"), "x" : 1, "class" : "三年二班", "lastModified" : ISODate("2022-01-05T12:36:17.008Z"), "teacher" : "gaoSeng" }
>
>
> db.myCollection.replaceOne({x:1},{name:"x1",age:11})
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
>
>
# 替换了第一个文档,可以发现_id没有变化
> db.myCollection.find( {} )
{ "_id" : ObjectId("61d52c33875bb4c2408d6e53"), "name" : "x1", "age" : 11 }
{ "_id" : ObjectId("61d58543875bb4c2408d6e54"), "x" : 1, "class" : "三年二班", "lastModified" : ISODate("2022-01-05T12:36:17.008Z"), "teacher" : "gaoSeng" }
{ "_id" : ObjectId("61d585e4875bb4c2408d6e55"), "name" : "alix", "age" : 30, "lastModified" : ISODate("2022-01-05T12:38:54.530Z") }
{ "_id" : ObjectId("61d585e4875bb4c2408d6e56"), "name" : "jenson", "age" : 18 }
{ "_id" : ObjectId("61d58605875bb4c2408d6e57"), "name" : "angila", "age" : 15 }
{ "_id" : ObjectId("61d58620875bb4c2408d6e58"), "name" : "blus", "age" : 15 }
{ "_id" : ObjectId("61d58620875bb4c2408d6e59"), "name" : "zhangSang", "age" : 18 }
{ "_id" : ObjectId("61d52c33875bb4c2408d6e60"), "x" : 1, "class" : "三年二班", "lastModified" : ISODate("2022-01-05T12:36:17.008Z"), "teacher" : "gaoSeng" }
>
>
# 没有replaceMany这个函数
> db.myCollection.replaceMany({x:1},{class:"三年二班",age:12})
uncaught exception: TypeError: db.myCollection.replaceMany is not a function :
@(shell):1:1
>
更多复杂crud其实官方文档很详细,需要时再找
springBoot使用MongoDB
参考博客:https://www.cnblogs.com/superjie/p/9722147.html
- 依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
- application.yml配置文件
spring:
application:
name: simple-spring-boot-demo
data:
mongodb:
database: myDB
host: 127.0.0.1
port: 27017
username: admin
password: 123456
项目启动报错:
2022-01-05 21:17:57.768 INFO 32920 --- [ main] org.mongodb.driver.cluster : Adding discovered server 127.0.0.1:27017 to client view of cluster
2022-01-05 21:17:57.993 INFO 32920 --- [127.0.0.1:27017] org.mongodb.driver.cluster : Exception in monitor thread while connecting to server 127.0.0.1:27017
com.mongodb.MongoSecurityException: Exception authenticating MongoCredential{mechanism=null, userName='admin', source='admin', password=<hidden>, mechanismProperties={}}
at com.mongodb.connection.SaslAuthenticator.wrapException(SaslAuthenticator.java:162) ~[mongodb-driver-core-3.6.4.jar:na]
at com.mongodb.connection.SaslAuthenticator.access$200(SaslAuthenticator.java:39) ~[mongodb-driver-core-3.6.4.jar:na]
at com.mongodb.connection.SaslAuthenticator$1.run(SaslAuthenticator.java:68) ~[mongodb-driver-core-3.6.4.jar:na]
at com.mongodb.connection.SaslAuthenticator$1.run(SaslAuthenticator.java:46) ~[mongodb-driver-core-3.6.4.jar:na]
at com.mongodb.connection.SaslAuthenticator.doAsSubject(SaslAuthenticator.java:168) ~[mongodb-driver-core-3.6.4.jar:na]
at com.mongodb.connection.SaslAuthenticator.authenticate(SaslAuthenticator.java:46) ~[mongodb-driver-core-3.6.4.jar:na]
at com.mongodb.connection.DefaultAuthenticator.authenticate(DefaultAuthenticator.java:32) ~[mongodb-driver-core-3.6.4.jar:na]
at com.mongodb.connection.InternalStreamConnectionInitializer.authenticateAll(InternalStreamConnectionInitializer.java:122) ~[mongodb-driver-core-3.6.4.jar:na]
at com.mongodb.connection.InternalStreamConnectionInitializer.initialize(InternalStreamConnectionInitializer.java:52) ~[mongodb-driver-core-3.6.4.jar:na]
at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:127) ~[mongodb-driver-core-3.6.4.jar:na]
at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:114) ~[mongodb-driver-core-3.6.4.jar:na]
at java.lang.Thread.run(Thread.java:748) [na:1.8.0_191]
Caused by: com.mongodb.MongoCommandException: Command failed with error 18: 'Authentication failed.' on server 127.0.0.1:27017. The full response is { "ok" : 0.0, "errmsg" : "Authentication failed.", "code" : 18, "codeName" : "AuthenticationFailed" }
解决方式参考:https://www.cnblogs.com/niwotaxuexiba/p/10642291.html 和 https://blog.csdn.net/qq_45186545/article/details/107553692
创建一个myDB下的账号
> use myDB
switched to db myDB
>
>
> db.createUser({user:"zhang_san",pwd:"123456",roles:["readWrite"]})
Successfully added user: { "user" : "zhang_san", "roles" : [ "readWrite" ] }
修改application.yml的连接配置,密码需要用单引号包起来
spring:
application:
name: simple-spring-boot-demo
data:
mongodb:
database: myDB
host: 127.0.0.1
port: 27017
username: zhang_san
password: '123456'
option:
max-connection-idle-time: 1500
max-connection-per-host: 200
max-wait-time: 60000
max-connection-life-time: 0
connect-timeout: 10000
socket-timeout: 60000
- 查询数据
import lombok.Data;
import java.util.Date;
/**
* @author Jenson
*/
@Data
public class MongoTestData {
private String name;
private Integer age;
private Date lastModified;
}
package com.jenson.controller.v1;
import com.jenson.entity.MongoTestData;
import lombok.extern.slf4j.Slf4j;
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 org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* @author Jenson
*/
@RestController
@RequestMapping("/mongo")
@Slf4j
public class MongoDbController {
@Autowired
private MongoTemplate mongoTemplate;
@GetMapping()
public List<MongoTestData> searchData(@RequestParam String param,
@RequestParam String value) {
Query query = new Query();
Criteria criteria = Criteria.where(param).is(value);
query.addCriteria(criteria);
List<MongoTestData> list = mongoTemplate.find(query, MongoTestData.class, "myCollection");
return list;
}
}
使用的操作mongo的bean是MongoTemplate
,详细操作可以查看源码
调用测试
http://localhost:8010/mongo?param=name&value=alix
[
{
"name": "alix",
"age": 30,
"lastModified": "2022-01-05T12:38:54.530+0000"
}
]
网友评论