本文已参加「新人创作礼」活动,一起开启掘金创作之路
安装
- 下载地址,版本选择正确否则运行时会出现
zsh: exec format error
- 下载
wget https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-rhel70-4.4.13.tgz
- 解压进入目录
tar -zxvf mongodb-linux-x86_64-rhel70-4.4.13.tgz -C /usr/local &&cd /usr/local/mongodb-linux-x86_64-rhel70-4.4.13
- 创建数据存放文件夹
mkdir -p data/db
- 创建日志存放文件夹
mkdir log
- 指定数据文件夹日志输出后台启动
./bin/mongod --dbpath data/db --logpath log/output --fork
操作
用户管理
- 连接数据库
./bin/mongo --host 127.0.0.1 --port 27017
- 使用admin数据库
use admin
- 创建用户
db.createUser({"user":"jamin","pwd":"123456","roles":["root"]})
- 查看用户
show users
操作数据
- mongodb与关系型数据库的概念对比
| 关系型数据库 | mongodb | 说明 |
|---|
| database | database | 数据库 |
| table | collection | 表/集合 |
| row | docment | 行/文件 |
| column | field | 列/字段 |
| index | index | 索引 |
| tables join | | 表关联 |
| primary key | primary key | 主键,mongodb默认_id作为主键 |
- 创建数据库
- 使用
use test数据库不存在自动创建数据库否则切换数据库
- 插入数据
db.集合.insertOne(json字符串)
- 基础使用
db.user.insertOne({"name":"jamin","age":12})
db.user.insertMany([{"name":"zhangsan","age":18},{"name":"lisi","age":15}])
db.user.insert([{"name":"zhangsan2","age":20},{"name":"lisi2","age":19}])
- writeConcern安全写级别
- w:0(不反悔任何)1/>1(要求确认操作传播到指定数量的mongod实例上)majority(写入操作已经传递到绝大多数投票节点和主节点上)
- j:是否确认写入到journal日志上
- wtimeout:单位ms 写入节点超时时间,超时后会返回错误不会撤销之前节点的写入
- 主键字段_id
- 复合主键(注意顺序):db.user.insert({_id:{name:"test",age:12}})
- insert,insertOne,insertMany的区别:insert支持explain命令,其他不支持
查询
- 基础使用
db.user.find({});
db.user.find({name:"jamin"});
db.user.find({name:"jamin",age:12});
db.user.insertOne({name:"jaminye",age:18,school:{name:"清华大学附属中学",addr:"北京"}});
db.user.find({"school.addr":"北京"});
db.user.find({},{name:1,_id:0});
db.user.find({$and: [{name:"jamin"},{age:12}]});
db.user.find({$or: [{name:"jamin"},{age:18}]});
db.user.find({age:{$gte:18}});
- 条件与mysql对照
| mysql | mongodb |
|---|
| field!=1或<>1 | {field:{$ne:1}} |
| field>1 | {field:{$gt:1}} |
| field>=1 | {field:{$gte:1}} |
| field < 1 | {field:{$lt:1}} |
| field<=1 | {field:{$lte:1}} |
| field in (1,2) | {field:{$in:[1,2]}} |
| field not in (1,2) | {field:${nin:[1,2]}} |
| field is null | {field:{$exists:false}} |
- 分页
- skip(int) 跳过几个
- limit(int) 查询出几个
- count(boolen) 总数,参数为是否考虑skip和limit默认不考虑
- sort() 排序:{age:-1} 1从小到大 -1 从大到小
db.user.find({}).sort({age:-1}).skip(0).limit(5)
- 数组切割slice(limit/[skip,limit])
db.user.find({name:'testArr'},{addr:{slice: [1,2]}})
- 数组增加条件(符合前面条件的都会返回,再进行操作)db.user.find({}, { addr: { elemMatch: { eq: "上海" } } });
更新操作
db.user.updateOne({name:"jaminye"},{$set: {flag:1}}})
db.user.updateMany({name:"jaminye"},{$set:{flag:10}})
db.user.update({name:"jaminye"},{$set: {flag:1}},{multi:true})
db.user.updateMany({name:"jaminye"},{$rename: {flag:"flag1"}});
db.user.updateMany({name:"jaminye"},{$inc: {flag:2}})
db.user.updateMany({name:"jaminye"},{$min: {flag:12}})
db.user.updateMany({name:"jaminye"},{$max: {flag:8}})
db.test.drop({writeConcern:{w:1}})
db.user.remove({name:"jaminye"}, {writeConcern:{w:1}},{justOne: true});
db.user.deleteOne({name:"jaminye"},{writeConcern:{w:1}});
db.user.deleteMany({name:"jaminye"},{writeConcern:{w:1}});
聚合操作
db.orders.insertMany([
{
orderId: "0001", orderName: "jamin", orders: [
{
product: "xiaomi6", price: 1999
},
{
product: "xiaomi7", price: 2999
},
{
product: "xiaomi12", price: 3999
}
]
},
{
orderId: "0002", orderName: "jamin1", orders: [
{
product: "xiaomi8", price: 1999
},
{
product: "huaweimate12", price: 3999
}
]
}, {
orderId: "0003", orderName: "jamin10", orders: [
{
product: "ipad", price: 5999
},
{
product: "huaweimate30 pro", price: 6999
}
]
}
]);
db.orders.aggregate([
{ $addFields: { "totalPrice": { $sum: "$orders.price" } } },
{ $sort: { "totalPrice": 1 } },
{ $limit: 1 }])
db.orders.aggregate({ $project: { "订购者": "$orderName", "orderId": 1 } })
db.orders.aggregate({ $match: { "orders.product": "xiaomi8", "orders.price": { $gte: 1000 } } })
db.orders.aggregate({ $skip: 1 }, { $limit: 1 }, { $sort: { "orders.price":-1 } });
db.test.insertMany([{ "province": "江苏", "city": ["南京", "苏州", "无锡"] }, { "province": "广东", "city": ["广州", "深圳", "东莞"] }, { "province": "广西", "city": [] }]);
db.test.aggregate({ $unwind: { path: "$city", includeArrayIndex: "index", preserveNullAndEmptyArrays: true } })
db.students.insertMany([{ "name": "zhangsna", "class": 1 }, { "name": "lisi", "class": 1 }, { "name": "wangwu", "class": 2 }]);
db.class.insertMany([{ "class_id": 1, "name": "三年级二班" }, { "class_id": 2, "name": "四年级三班" }]);
db.students.aggregate({
$lookup: {
from: "class",
localField: "class",
foreignField: "class_id",
as: "className"
}
})
db.fruit.find({})
db.fruit.insertMany(
[{ "time": ISODate("2022-01-11T08:00:00Z"), "item": "apple", "price": 3.5, count: 10 },
{ "time": ISODate("2022-01-11T08:00:00Z"), "item": "apple", "price": 3.8, count: 18 },
{ "time": ISODate("2022-01-11T08:00:00Z"), "item": "orange", "price": 4, count: 10 },
{ "time": ISODate("2022-01-12T08:00:00Z"), "item": "orange", "price": 5, count: 8 },
{ "time": ISODate("2022-01-13T08:00:00Z"), "item": "orange", "price": 3.5, count: 10 },
{ "time": ISODate("2022-01-14T08:00:00Z"), "item": "pear", "price": 5.5, count: 10 },
{ "time": ISODate("2022-01-14T08:00:00Z"), "item": "apple", "price": 3.5, count: 10 }
]);
db.fruit.aggregate({
$group: {
_id: { "day": { $dayOfYear: "$time" },"month":{$month: "$time"}, "year": { $year: "$time" } }
, "item": { $addToSet: "$item" }
}
})
db.fruit.aggregate({
$group: {
_id: { "day": { $dayOfYear: "$time" },"month":{$month: "$time"}, "year": { $year: "$time" } }
, "item": { $addToSet: "$item" }
}
})
db.fruit.aggregate({
$group: { _id: "$item","itemPrice":{$avg: "$price"}}
})
db.fruit.aggregate({$group: { _id:
{ "day": { $dayOfYear: "$time" },"month":{$month: "$time"}, "year": { $year: "$time" } },
"itemsSold":{ $push: { item: "$item", "count": "$count" } }
}})
db.fruit.aggregate({$group: { _id:{ "day": { $dayOfYear: "$time" },"month":{$month: "$time"}, "year": { $year: "$time" } },
"itemsSold":{ $push: { item: "$item", "count": "$count" } }}
})
db.fruit.aggregate({$group: { _id:{ "day": { $dayOfYear: "$time" },"month":{$month: "$time"}, "year": { $year: "$time" } },
"itemsSold":{ $push: { item: "$item", "count": "$count" } }}
},{$out: "out"})
db.out.find({})