https://www.mongodb.com/try/download/community
我这里是将MongoDB搭建在Linux上的
上传至Linux服务器上,解压,安装即可
解压
tar zxvf mongodb-linux-x86_64-rhel70-4.0.28.tgz
移动并且修改名字
mv mongodb-linux-x86_64-rhel70-4.0.28 /usr/local/mongodb4.0.28
进入文件夹
cd /usr/local/mongodb4.0.28
新建文件夹
mkdir data data/db data/log
修改文件夹权限
sudo chmod 666 data/db data/log/
新建配置文件
vim mongodb.conf
# 内容如下
# 数据库数据存放目录
dbpath=/usr/local/mongodb4.0.28/data/db
# 日志文件存放目录
logpath=/usr/local/mongodb4.0.28/data/log/mongodb.log
# 日志追加方式
logappend=true
# 端口
port=27017
# 是否认证
auth=true
# 以守护进程方式在后台运行
fork=true
# 远程连接要指定ip,否则无法连接;0.0.0.0代表不限制ip访问
bind_ip=0.0.0.0
配置环境变量
sudo vi /etc/profile
# 添加内容如下
export MONGODB_HOME=/usr/local/mongodb4.0.28
export PATH=$PATH:$MONGODB_HOME/bin
# 生效
source /etc/profile
mongod -f /usr/local/mongodb4.0.28/mongodb.conf
mongo
db
新建用户和配置密码
> db
test
> use admin
switched to db admin
> db.createUser({user:"admin",pwd:"123456",roles:[{role:"userAdminAnyDatabase",db:"admin"}]})
Successfully added user: {
"user" : "admin",
"roles" : [
{
"role" : "userAdminAnyDatabase",
"db" : "admin"
}
]
}
> db.auth("admin","123456")
1
> use nobody
switched to db nobody
> db.createUser({user:'mao',pwd:'123456',roles:[{role:'readWrite',db:'nobody'}]})
Successfully added user: {
"user" : "mao",
"roles" : [
{
"role" : "readWrite",
"db" : "nobody"
}
]
}
windows 测试连接
验证那使用账户和密码进行验证
admin
123456
退出MongoDB的数据库
exit
查看服务
[root@localhost mongodb4.0.28]# ps aux | grep mongo
root 2893 0.6 3.6 1104088 55112 ? SLl 08:45 0:14 mongod -f /usr/local/mongodb4.0.28/mongodb.conf
root 3432 0.0 0.0 112824 988 pts/0 S+ 09:23 0:00 grep --color=auto mongo
查看端口是否启用
[root@localhost mongodb4.0.28]# netstat -lanp | grep 27017
tcp 0 0 0.0.0.0:27017 0.0.0.0:* LISTEN 2893/mongod
tcp 0 0 127.0.0.1:34040 127.0.0.1:27017 TIME_WAIT -
unix 2 [ ACC ] STREAM LISTENING 42346 2893/mongod /tmp/mongodb-27017.sock
[root@localhost mongodb4.0.28]#
如果 netstat 命令没有找到,先进行安装
yum install -y net-tools
关闭服务,进程杀死或者通过mongod命令关闭mongodb服务
[root@localhost mongodb4.0.28]# kill -9 2893
[root@localhost mongodb4.0.28]# ps aux | grep mongo
root 3486 0.0 0.0 112824 988 pts/0 S+ 09:26 0:00 grep --color=auto mongo
[root@localhost mongodb4.0.28]# mongo
MongoDB shell version v4.0.28
connecting to: mongodb://127.0.0.1:27017/?gssapiServiceName=mongodb
2022-10-16T09:27:20.923+0800 E QUERY [js] Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed: SocketException: Error connecting to 127.0.0.1:27017 :: caused by :: Connection refused :
connect@src/mongo/shell/mongo.js:356:17
@(connect):2:6
exception: connect failed
[root@localhost mongodb4.0.28]#
再次开启和通过MongoDB自带命令关闭
[root@localhost mongodb4.0.28]# mongod -f /usr/local/mongodb4.0.28/mongodb.conf
about to fork child process, waiting until server is ready for connections.
forked process: 3500
child process started successfully, parent exiting
[root@localhost mongodb4.0.28]# mongo
MongoDB shell version v4.0.28
connecting to: mongodb://127.0.0.1:27017/?gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("bfc39d18-d7e0-4e93-bfa5-2261de8bc82c") }
MongoDB server version: 4.0.28
> exit
bye
[root@localhost mongodb4.0.28]# ps aux | grep mongo
root 3500 12.0 3.5 1096772 53668 ? Sl 09:28 0:01 mongod -f /usr/local/mongodb4.0.28/mongodb.conf
root 3537 0.0 0.0 112824 984 pts/0 R+ 09:28 0:00 grep --color=auto mongo
[root@localhost mongodb4.0.28]# netstat -lanp | grep 27017
tcp 0 0 0.0.0.0:27017 0.0.0.0:* LISTEN 3500/mongod
tcp 0 0 127.0.0.1:34044 127.0.0.1:27017 TIME_WAIT -
unix 2 [ ACC ] STREAM LISTENING 50768 3500/mongod /tmp/mongodb-27017.sock
[root@localhost mongodb4.0.28]# mongod -f /usr/local/mongodb4.0.28/mongodb.conf --shutdown
killing process with pid: 3500
一定要先登录admin,在创建root用户并且设置密码,再使用root的信息登录,在进行操作
> use admin
switched to db admin
> db.createUser({user:"root",pwd:"123456",roles:[{role:"root",db:"admin"}]})
2022-10-21T10:24:41.029+0800 E QUERY [js] Error: couldn't add user: User "root@admin" already exists :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
DB.prototype.createUser@src/mongo/shell/db.js:1513:15
@(shell):1:1
> db.auth('root','123456')
1
> db.system.users.findOne({})
{
"_id" : "admin.admin",
"userId" : UUID("10656360-e092-4a8b-8816-b82081c7f71f"),
"user" : "admin",
"db" : "admin",
"credentials" : {
"SCRAM-SHA-1" : {
"iterationCount" : 10000,
"salt" : "t9QXx+QLt0aATDDMVD8jWQ==",
"storedKey" : "MLXCznjZgj3Wpp0a07W5ksh6gLg=",
"serverKey" : "6GcA/x/ZaB6fJ2NxhNCg8HJPCVQ="
},
"SCRAM-SHA-256" : {
"iterationCount" : 15000,
"salt" : "rJ5pz+kYUl5NjrwElYvcBLJnodLfm69Tg9x30Q==",
"storedKey" : "3d2vB9qW+xXaHe4wA/0WMJ4t+oo+C6/pak0AVghIgA8=",
"serverKey" : "dQi4CenFkiri3tAn8G2mS8VwfDWUWjAK7AbIrU4be5w="
}
},
"roles" : [
{
"role" : "userAdminAnyDatabase",
"db" : "admin"
}
]
}
> use db1
switched to db db1
> db.person.insert({"name":"mao"})
WriteResult({ "nInserted" : 1 })
> db.person.find()
{ "_id" : ObjectId("635203246bc5f3d928d216e7"), "name" : "mao" }
查看所有的数据库
show dbs
删除数据库
db.dropDatabase()
删除集合
db.collection.drop()
当你插入一些文档时,MongoDB 会自动创建集合。
> db.s.insert({"name" : "hello"})
WriteResult({ "nInserted" : 1 })
> show tables
mycol
s
student
创建集合
> db.createCollection("student")
{ "ok" : 1 }
自定义创建集合,自带自增的id索引和尺寸,最大值
> db.createCollection("mycol", { capped : true, autoIndexId : true, size :
... 6142800, max : 10000 } )
{
"note" : "the autoIndexId option is deprecated and will be removed in a future release",
"ok" : 1
}
删除集合,将集合全部删除,查看
> show collections
mycol
s
student
> db.mycol.drop()
true
> db.s.drop()
true
> db.student.drop()
true
> show collections
清屏
cls
插入文档和变量代替,插入变量
> use db1
switched to db db1
> db.col.insert({title: "MongoDB 学习",description: "MongoDB 是一个文档型的非关系型数据库",by: "coffeemao",url: "www.coffeemao.com",tags: ['mongoDB','DATABASE','NoSQL'],like: 100})
WriteResult({ "nInserted" : 1 })
> db.col.find()
{ "_id" : ObjectId("63520d0a508aa67aae48a3e0"), "title" : "MongoDB 学习", "description" : "MongoDB 是一个文档型的非关系型数据库", "by" : "coffeemao", "url" : "www.coffeemao.com", "tags" : [ "mongoDB", "DATABASE", "NoSQL" ], "like" : 100 }
> document=({title: "MongoDB 学习",description: "MongoDB 是一个文档型的非关系型数据库",by: "coffeemao",url: "www.coffeemao.com",tags: ['mongoDB','DATABASE','NoSQL'],like: 100});
> db.col2.insert(document)
WriteResult({ "nInserted" : 1 })
> show tables
col
col2
> db.col2.find()
{ "_id" : ObjectId("63520d64508aa67aae48a3e1"), "title" : "MongoDB 学习", "description" : "MongoDB 是一个文档型的非关系型数据库", "by" : "coffeemao", "url" : "www.coffeemao.com", "tags" : [ "mongoDB", "DATABASE", "NoSQL" ], "like" : 100 }
>
修改文档
> db.col.find()
{ "_id" : ObjectId("63520d0a508aa67aae48a3e0"), "title" : "MongoDB 学习", "description" : "MongoDB 是一个文档型的非关系型数据库", "by" : "coffeemao", "url" : "www.coffeemao.com", "tags" : [ "mongoDB", "DATABASE", "NoSQL" ], "like" : 100 }
> db.col.update({'title':"MongoDB 学习"},{$set:{'title':"MongoDB 的Update操作"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.col.find()
{ "_id" : ObjectId("63520d0a508aa67aae48a3e0"), "title" : "MongoDB 的Update操作", "description" : "MongoDB 是一个文档型的非关系型数据库", "by" : "coffeemao", "url" : "www.coffeemao.com", "tags" : [ "mongoDB", "DATABASE", "NoSQL" ], "like" : 100 }
>
save的修改,根据id实现覆盖
> db.col.find()
{ "_id" : ObjectId("63520d0a508aa67aae48a3e0"), "title" : "MongoDB 的Update操作", "description" : "MongoDB 是一个文档型的非关系型数据库", "by" : "coffeemao", "url" : "www.coffeemao.com", "tags" : [ "mongoDB", "DATABASE", "NoSQL" ], "like" : 100 }
> db.col.save({"_id":ObjectId("63520d0a508aa67aae48a3e0"),"title":"MongoDB just Save"})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.col.find()
{ "_id" : ObjectId("63520d0a508aa67aae48a3e0"), "title" : "MongoDB just Save" }
>
文档的删除
> db.col.find()
{ "_id" : ObjectId("63520d0a508aa67aae48a3e0"), "title" : "MongoDB just Save" }
> db.col.remove({title:"MongoDB just Save"})
WriteResult({ "nRemoved" : 1 })
> db.col.find()
>
全部删除
db.col.remove({})
pretty查询
> db.col2.find().pretty()
{
"_id" : ObjectId("63520d64508aa67aae48a3e1"),
"title" : "MongoDB 学习",
"description" : "MongoDB 是一个文档型的非关系型数据库",
"by" : "coffeemao",
"url" : "www.coffeemao.com",
"tags" : [
"mongoDB",
"DATABASE",
"NoSQL"
],
"like" : 100
}
MongoDB AND 条件
b.col.find({"by":"hello", "title":"MongoDB 学习"}).pretty()
OR 操作
db.col.find({$or:[{"by":"hello"},{"title": "MongoDB 学习"}]}).pretty()
大于等的运算符操作
> db.col.insert({
... title: 'PHP 教程',
... description: 'PHP 是一种创建动态交互性站点的强有力的服务器端脚本语言。',
... by: '菜鸟教程',
... url: 'http://www.runoob.com',
... tags: ['php'],
... likes: 200
... })
WriteResult({ "nInserted" : 1 })
> db.col.insert({title: 'Java 教程',
... description: 'Java 是由Sun Microsystems公司于1995年5月推出的高级程序设计语言。',
... by: '菜鸟教程',
... url: 'http://www.runoob.com',
... tags: ['java'],
... likes: 150
... })
WriteResult({ "nInserted" : 1 })
> db.col.insert({title: 'MongoDB 教程',
... description: 'MongoDB 是一个 Nosql 数据库',
... by: '菜鸟教程',
... url: 'http://www.runoob.com',
... tags: ['mongodb'],
... likes: 100
... })
WriteResult({ "nInserted" : 1 })
> db.col.find()
{ "_id" : ObjectId("635212af847289e61996421d"), "title" : "PHP 教程", "description" : "PHP 是一种创建动态交互性站点的强有力的服务器端脚本语言。", "by" : "菜鸟教程", "url" : "http://www.runoob.com", "tags" : [ "php" ], "likes" : 200 }
{ "_id" : ObjectId("635212b9847289e61996421e"), "title" : "Java 教程", "description" : "Java 是由Sun Microsystems公司于1995年5月推出的高级程序设计语言。", "by" : "菜鸟教程", "url" : "http://www.runoob.com", "tags" : [ "java" ], "likes" : 150 }
{ "_id" : ObjectId("635212bf847289e61996421f"), "title" : "MongoDB 教程", "description" : "MongoDB 是一个 Nosql 数据库", "by" : "菜鸟教程", "url" : "http://www.runoob.com", "tags" : [ "mongodb" ], "likes" : 100 }
> db.col.find({likes:{$gt:100}})
{ "_id" : ObjectId("635212af847289e61996421d"), "title" : "PHP 教程", "description" : "PHP 是一种创建动态交互性站点的强有力的服务器端脚本语言。", "by" : "菜鸟教程", "url" : "http://www.runoob.com", "tags" : [ "php" ], "likes" : 200 }
{ "_id" : ObjectId("635212b9847289e61996421e"), "title" : "Java 教程", "description" : "Java 是由Sun Microsystems公司于1995年5月推出的高级程序设计语言。", "by" : "菜鸟教程", "url" : "http://www.runoob.com", "tags" : [ "java" ], "likes" : 150 }
操作符
db.col.find({title:{$type:2}})
limit
skip,跳过几个再开始
db.col.find({},{"title":1,_id:0}).sort({"like":-1})
索引的查看,创建,删除全部,删除指定,查看索引大小
> db.col.getIndexes()
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "db1.col"
}
]
> db.col.totalIndexSize()
36864
> db.col.dropIndex("_id_")
{
"ok" : 0,
"errmsg" : "cannot drop _id index",
"code" : 72,
"codeName" : "InvalidOptions"
}
> db.col.createIndex({"title":1})
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
> db.col.getIndexes()
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "db1.col"
},
{
"v" : 2,
"key" : {
"title" : 1
},
"name" : "title_1",
"ns" : "db1.col"
}
]
> db.col.dropIndex("title")
{
"ok" : 0,
"errmsg" : "index not found with name [title]",
"code" : 27,
"codeName" : "IndexNotFound"
}
> db.col.dropIndex("title_1")
{ "nIndexesWas" : 2, "ok" : 1 }
> db.col.dropIndexes()
{
"nIndexesWas" : 1,
"msg" : "non-_id indexes dropped for collection",
"ok" : 1
}
>
MongoDB 复制(副本集)
复制:数据同步在多个服务器中,复制提供了数据的冗余备份,多个服务器中提供了备份,保证了数据的安全性和可用性。复制还允许数据的备份和故障的恢复
什么是复制?
保障数据的安全性
数据高可用性 (24*7)
灾难恢复
无需停机维护(如备份,重建索引,压缩)
分布式读取数据
复制准备就是至少需要两个节点,一个主节点,一个从节点,主节点负责处理客户端的请求,从节点负责从主节点上拷贝数据,减少主节点的压力
客户端从主节点读取数据,在客户端写入数据到主节点时, 主节点与从节点进行数据交互保障数据的一致性。
java连接MongoDB
public static void main(String[] args) {
try {
MongoClient mongoClient = new MongoClient("192.168.152.129", 27107);
MongoDatabase database = mongoClient.getDatabase("col");
System.out.println("success");
}catch (Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}