mongodb搭建和使用
Mongo安装和启动
在linux环境下搭建单节点mongodb,步骤如下:
1.解压
tar -xzvf mongodb-linux-x86_64-3.4.6.tgz -C /usr/local/
2.改名
mv mongodb-linux-x86_64-3.4.6 mongodb
3.建立目录
mkdir -p /usr/local/mongodb/conf
mkdir -p /usr/local/mongodb/config
mkdir -p /usr/local/mongodb/config/data
mkdir -p /usr/local/mongodb/config/log
4.配置环境变量
vim /etc/profile
export MONGODB_HOME=/usr/local/mongodb
export PATH=$MONGODB_HOME/bin:$PATH
source /etc/profile
5. config server配置
vi /usr/local/mongodb/conf/config.conf
pidfilepath = /usr/local/mongodb/config/log/configsrv.pid
dbpath = /usr/local/mongodb/config/data
logpath = /usr/local/mongodb/config/log/congigsrv.log
logappend = true
bind_ip = 192.168.1.100 #(bind_ip参数,将本地IP赋予此参数。赋予后使用Server IP登入可以,但此时使用localhost 失败。为了同时兼容2种登入方式,将参数的赋值调整为:bind_ip=localhost,192.XXX.XXX.XXX 或设置为0.0.0.0)
port = 21000
fork = true # (后台启动)
#设置最大连接数
maxConns=20000
auth=true
6.后台启动Mongo
mongod -f /usr/local/mongodb/conf/config.conf
新增用户
use admin
db.createUser(
{
user:"admin",
pwd:"123456",
roles:["root"],
mechanisms : ["SCRAM-SHA-1"]
}
)
db.createUser(
{
user: "yyd",
pwd: "yyd",
roles: [ { role: "readWrite", db: "test" } ] #读写帐号
}
)
登录数据库
新增数据
查询数据
更新数据
删除数据
shell 命令
//创建用户
use test
db.createUser(
{
user: "admin",
pwd: "123456",
roles: ["root"],
mechanisms: ["SCRAM-SHA-1"]
}
)
db.createUser(
{
user: "yyd",
pwd: "yyd",
roles: [{ role: "readWrite", db: "test" }]
}
)
//多个新增 单个新增使用对象
db.getCollection("def_student").insertMany([{ "name": "wo", "age": "19" }])
//查询
// i 大小写不敏感
// m 查询匹配中使用了锚,例如^(代表开头)和$(代表结尾),以及匹配n后的字符串
// x 忽视所有空白字符,要求$regex与$option合用
// s 允许点字符(.)匹配所有的字符,包括换行符。要求$regex与$option合用
db.getCollection("def_student").find(
{
"$or": [{ "name": "test" }, { "name": "test1" }],
"name": { "$regex": "test", "$options": "" },
"birth": { "$gte": "2020-04-19 14:34:50", "$lte": "2020-04-22 13:34:50" },
"age": { "$in": ["18", "19", "20"] },
"num": 1.2,
"arr": { "$elemMatch": { "or": [{ "name": "test" }, { "name": "test1" }] } }
},
{"age":0,"name":0}
).sort(
{
"age": -1, //desc
"num": 1 //asc
}
).skip(10).limit(10)
// { $set: { "num": 1.9 } }
// { "$addToSet" : { "param6" : { "$each" : [ { "k1" : "v3"} , { "k2" : "v"}] }, "param7" : [ { "k1" : "v3"} , { "k2" : "v"}] } }
// { "$pull" : { "param1" : { "k1" : "v1" } } }
db.getCollection("def_student").update(
{ _id: ObjectId("63a158a32e7ceb44d0bb141c") },
{ "$pull": { "param2": { "k1": "v3" } } }
)
//aggregate
db.getCollection("def_student").aggregate(
[
{ "$match": { "name": { "$regex": "test", "$options": "i" } } },
{
"$group":
{
"_id": { "name": "$name", "age": "$age" },
"sum": { "$sum": "$num" },
"avg": { "$avg": "$num" },
"count": { "$sum": 1 },
"num_addToSet": { "$addToSet": "$num" },
"num_push": { "$push": "$num" },
"num_first": { "$first": "$num" },
"num_last": { "$last": "$num" },
"num_min": { "$min": "$num" },
"num_max": { "$max": "$num" }
}
},
{ "$sort": { "num": -1 } },
{ "$skip": { "$numberLong": "0" } },
{ "$limit": { "$numberLong": "100" } }
]
)