Mongodb 安装使用

简介

MongoDB 将数据记录作为文档存储在集合中。数据库存储一个或多个文档集合。(所以要先创建集合然后在集合内创建数据文档)。
如果集合不存在,MongoDB 会在您首次存储该集合的数据时创建该集合。
存储结构为:数据库 >> 集合 >> 文档。
数据类型:BSON。文档的数据结构和 JSON 基本一样。所有存储在集合中的数据都是 BSON 格式。BSON 是一种类似 JSON 的二进制形式的存储格式,是 Binary JSON 的简称。

Linux 安装、卸载

点击这里进入官网下载安装入口

# 使用yum安装 添加repo库地址
vim /etc/yum.repos.d/mongodb-org-5.0.repo

# 复制一下内容到文件内
[mongodb-org-5.0]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/5.0/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-5.0.asc

# 安装
yum install -y mongodb-org

# 卸载
# 停止服务
service mongod stop
# 删除mongoDB包
yum erase $(rpm -qa | grep mongodb-org)
# 删除MongoDB数据库和日志文件
rm -r /var/log/mongodb
rm -r /var/lib/mongo

介绍

默认配置

1、默认情况下,MongoDB 使用mongod用户帐户运行并使用以下默认目录。包管理器在安装期间创建默认目录。所有者和组名称是mongod

/var/lib/mongo(数据目录)
/var/log/mongodb(日志目录
drwxr-xr-x   2 mongod   mongod   4096 Jan 28 01:40 mongo

2、配置文件路径 /etc/mongod.conf

自定义配置

1、如果要使用默认目录以外的数据目录和/或日志目录:

创建一个或多个新目录。
编辑配置文件/etc/mongod.conf并相应地修改以下字段:

	storage.dbPath指定新的数据目录路径(例如/some/data/directory)
	systemLog.path指定新的日志文件路径(例如/some/log/directory/mongod.log)

确保运行 MongoDB 的用户有权访问一个或多个目录:

sudo chown -R mongod:mongod

如果更改运行 MongoDB 进程的用户,则必须 授予新用户对这些目录的访问权限.

启动

# 启动
systemctl start mongod
# 查看状态
systemctl status mongod
# 设置开机启动
systemctl enable mongod
# 停止
systemctl stop mongod
# 重启
systemctl restart mongod

#配置环境变量
/var/lib/mongosh

使用

进入到 /usr/bin 目录下使用 或者配置环境变量后使用
Tips:MongoDB 中默认的数据库为 test,如果你没有创建新的数据库,集合将存放在 test 数据库中。

# 命令行进入  localhost 上运行的默认端口 27017
$ mongosh

# 查看所有数据库
$ test> show dbs
	admin     41 kB
	config  49.2 kB
	local     41 kB

# 查看当前数据库
$ db
	test

# 切换数据库(切换前无需创建数据库。MongoDB 在您第一次在该数据库中存储数据时创建数据库)
$ test> use hello
	switched to db hello

# 删除数据库(进入到要删除的数据库内,执行 db.dropDatabase() )
$ hello> db.dropDatabase()
{ ok: 1, dropped: 'hello' }

# 创建集合 db.createCollection(name, options)
# 参数:
# capped: (可选)如果为 true,则创建固定集合。固定集合是指有着固定大小的集合,当达到最大值时,它会自动覆盖最早的文档。当该值为 true 时,必须指定 size 参数。
# autoIndexId: 3.2 之后不再支持该参数。(可选)如为 true,自动在 _id 字段创建索引。默认为 false。
# size:(可选)为固定集合指定一个最大值,即字节数。如果 capped 为 true,也需要指定该字段。
# max: (可选)指定固定集合中包含文档的最大数量。

# 不指定参数创建集合
$ hello> show collections
	collection1
$ hello> db.createCollection("one")
	{ ok: 1 }
$ hello> show collections
	collection1
	one
# 指定参数创建集合
$ hello> db.createCollection("name1", {capped: true, size: 20, max: 2})
	{ ok: 1 }
$ hello> show collections
	collection1
	name1
	one

# 查看所有集合
$ hello> show tables
	collection1
$ hello> show collections
	collection1

# 删除集合
$ hello> db.collection_name.drop()
	true


# 插入文档 db.COLLECTION_NAME.insertOne(document) 或 db.COLLECTION_NAME.save(document)
$ hello> db.name1.insertOne({"2": 2})  # 插入一条
{
  acknowledged: true,
  insertedId: ObjectId("621ec8c81d216f37410dc0fc")
}
$ hello> db.name1.insertMany([{"3": 3}, {"4":4}])  #插入多条
{
  acknowledged: true,
  insertedIds: {
    '0': ObjectId("621ec8e61d216f37410dc0fd"),
    '1': ObjectId("621ec8e61d216f37410dc0fe")
  }
}


# 更新文档 db.collection_name.updateOne()  db.collection_name.updateMany()
# 参数说明:
# query : update的查询条件,类似sql update查询内where后面的。
# update : update的对象和一些更新的操作符(如$set,$inc...)等,也可以理解为sql update查询内set后面的
# upsert : 可选,这个参数的意思是,如果不存在update的记录,是否插入objNew,true为插入,默认是false,不插入。
# multi : 可选,mongodb 默认是false,只更新找到的第一条记录,如果这个参数为true,就把按条件查出来多条记录全部更新。
# writeConcern :可选,抛出异常的级别。
hello> db.one.find()
[ { '1': 3, _id: ObjectId("621ecaee1d216f37410dc101"), en: 'en' } ]
hello> db.one.updateOne({"1":3},{$set:{"1":4, "age":1}})
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}
hello> db.one.find()
[
  {
    '1': 4,
    _id: ObjectId("621ecaee1d216f37410dc101"),
    en: 'en',
    age: 1
  }
]

# 使用$inc 只能用于数字类型,而且是递增的算法,每次使用在原有基础上增加指定数值
$ hello> db.one.find({'name': 'a1'})
[
  {
    _id: ObjectId("621f379867ec5338709bcebf"),
    name: 'a1',
    age: 120,
    class: '一年级四班'
  }
]
$ hello> db.one.updateOne({'name': 'a1'}, {$inc: {'age': 5}})
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}
$ hello> db.one.find({'name': 'a1'})
[
  {
    _id: ObjectId("621f379867ec5338709bcebf"),
    name: 'a1',
    age: 125,
    class: '一年级四班'
  }
]
$ hello> db.one.updateOne({'name': 'a1'}, {$inc: {'age': 6}})
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}
$ hello> db.one.find({'name': 'a1'})
[
  {
    _id: ObjectId("621f379867ec5338709bcebf"),
    name: 'a1',
    age: 131,
    class: '一年级四班'
  }
]


# 删除文档 db.collection_name.deleteOne(), deleteMany, findOneAndDelete, bulkWrite, remove
# remove()方法参数说明:
# query :(可选)删除的文档的条件。
# justOne : (可选)如果设为 true 或 1,则只删除一个文档。
# writeConcern :(可选)抛出异常的级别。
$ hello> db.one.findOneAndDelete({"1":2})
null  # 如果找不到则返回 null
$ hello> db.one.findOneAndDelete({"1":1})
{ '1': 1, _id: ObjectId("621ece391d216f37410dc102") } # 如果找到了,则返回已删除文档

$ hello> db.one.remove({"name":"jony"})  # 根据条件查找并删除文档
{ acknowledged: true, deletedCount: 1 }  # 返回删除一条
$ hello> db.one.remove({"name":"jony"})
{ acknowledged: true, deletedCount: 0 }  # 如果没有匹配到,则返回删除0条
$ hello> db.one.deleteOne({"id":1})
{ acknowledged: true, deletedCount: 1 }
$ hello> db.one.remove({})  #  删除当前集合下的所有文档
{ acknowledged: true, deletedCount: 2 }


# 查询文档 db.collection_name.find()
| 释意 | 格式 | 示例 | 等效mysql |
| 等于 | {key: value} | db.collection_name.find({"id":1}) | where id = 1 |
| 小于 | {key: {$lt:value}} | db.collection_name.find({"id":{$lt:1}}) | where id < 1 |
| 小于等于 | {key: {$lte:value}} | db.collection_name.find({"id":{$lte:9}}) | where id <= 1 |
| 大于 | {key: {$gt:value}} | db.collection_name.find({"id":{$gt:3}}) | where id > 3 |
| 大于等于 | {key: {$gte:value}} | db.collection_name.find({"id":{$gte:3}}) | where id >= 3 |
| 不等于 | {key: {$ne:value}} | db.collection_name.find({"id":{$ne:8}}) | where id != 8 |

# 多条件查询  and
$ hello> db.one.find({"id":2,"name":"woli"})
[ { _id: ObjectId("621ed6f91d216f37410dc108"), id: 2, name: 'woli' } ]  # 查到了则返回文档
$ hello> db.one.find({"id":2,"name":"woli1"})
    # 没查到则返回为空

# 多条件查询 $or
$ hello> db.one.find()
[
  { _id: ObjectId("621ed6f91d216f37410dc108"), id: 2, name: 'woli' },
  { _id: ObjectId("621ed7791d216f37410dc109"), id: 2, name: 'heol' },
  { _id: ObjectId("621ed8411d216f37410dc10a"), id: 3, name: 'gana' },
  { _id: ObjectId("621ed8411d216f37410dc10b"), id: 4, name: 'bala' }
]
$ hello> db.one.find({$or:[{'id':2}, {'name':'woli'}]})
[
  { _id: ObjectId("621ed6f91d216f37410dc108"), id: 2, name: 'woli' },
  { _id: ObjectId("621ed7791d216f37410dc109"), id: 2, name: 'heol' }
]

# 多条件查询 and + $or
$ hello> db.one.find({'id': {$lt:9}, $or:[{'id':2}, {'name':'woli'}]})
[
  { _id: ObjectId("621ed6f91d216f37410dc108"), id: 2, name: 'woli' },
  { _id: ObjectId("621ed7791d216f37410dc109"), id: 2, name: 'heol' }
]

# 根据字段类型查找 $type 字段类型可选值:Double, String, Object, Array, Boolean, Date, Null, int, Timestamp, JavaScript, Symbol, Binary data, Object id, Regular Expression

$ hello> db.one.find({'id':{$type: 'int'}})
[
  { _id: ObjectId("621ed6f91d216f37410dc108"), id: 2, name: 'woli' },
  { _id: ObjectId("621ed7791d216f37410dc109"), id: 2, name: 'heol' },
  { _id: ObjectId("621ed8411d216f37410dc10a"), id: 3, name: 'gana' },
  { _id: ObjectId("621ed8411d216f37410dc10b"), id: 4, name: 'bala' }
]


# limit 
$ hello> db.one.find()
[
  { _id: ObjectId("621ed6f91d216f37410dc108"), id: 2, name: 'woli' },
  { _id: ObjectId("621ed7791d216f37410dc109"), id: 2, name: 'heol' },
  { _id: ObjectId("621ed8411d216f37410dc10a"), id: 3, name: 'gana' },
  { _id: ObjectId("621ed8411d216f37410dc10b"), id: 4, name: 'bala' }
]
$ hello> db.one.find().limit(2)
[
  { _id: ObjectId("621ed6f91d216f37410dc108"), id: 2, name: 'woli' },
  { _id: ObjectId("621ed7791d216f37410dc109"), id: 2, name: 'heol' }
]
$ hello> db.one.find({'id':{$gte:3}}).limit(2)
[
  { _id: ObjectId("621ed8411d216f37410dc10a"), id: 3, name: 'gana' },
  { _id: ObjectId("621ed8411d216f37410dc10b"), id: 4, name: 'bala' }
]

# limit + skip 
$ hello> db.one.find().limit(4).skip(3)
[ { _id: ObjectId("621ed8411d216f37410dc10b"), id: 4, name: 'bala' } ]
$ hello> db.one.find().limit(4).skip(2)
[
  { _id: ObjectId("621ed8411d216f37410dc10a"), id: 3, name: 'gana' },
  { _id: ObjectId("621ed8411d216f37410dc10b"), id: 4, name: 'bala' }
]

# 排序 sort() 使用 1 和 -1 来指定排序的方式,其中 1 为升序排列,而 -1 是用于降序排列。
$ hello> db.one.find().sort({'id':1})
[
  { _id: ObjectId("621ed6f91d216f37410dc108"), id: 2, name: 'woli' },
  { _id: ObjectId("621ed7791d216f37410dc109"), id: 2, name: 'heol' },
  { _id: ObjectId("621ed8411d216f37410dc10a"), id: 3, name: 'gana' },
  { _id: ObjectId("621ed8411d216f37410dc10b"), id: 4, name: 'bala' }
]
$ hello> db.one.find().sort({'id':-1})
[
  { _id: ObjectId("621ed8411d216f37410dc10b"), id: 4, name: 'bala' },
  { _id: ObjectId("621ed8411d216f37410dc10a"), id: 3, name: 'gana' },
  { _id: ObjectId("621ed6f91d216f37410dc108"), id: 2, name: 'woli' },
  { _id: ObjectId("621ed7791d216f37410dc109"), id: 2, name: 'heol' }
]


# 聚合 db.collection_name.aggregate()
# 管道操作符:
# $project:修改输入文档的结构。可以用来重命名、增加或删除域,也可以用于创建计算结果以及嵌套文档。
# $match:用于过滤数据,只输出符合条件的文档。$match使用MongoDB的标准查询操作。
# $limit:用来限制MongoDB聚合管道返回的文档数。
# $skip:在聚合管道中跳过指定数量的文档,并返回余下的文档。
# $unwind:将文档中的某一个数组类型字段拆分成多条,每条包含数组中的一个值。
# $group:将集合中的文档分组,可用于统计结果。
# $sort:将输入文档排序后输出。
# $geoNear:输出接近某一地理位置的有序文档。
# 聚合表达式:
# $sum, $avg, $min, $max, 
# $push, 将值加入一个数组中,不会判断是否有重复的值。
# $addToSet, 将值加入一个数组中,会判断是否有重复的值,若相同的值在数组中已经存在了,则不加入。
# $first, 根据资源文档的排序获取第一个文档数据。
# $last, 根据资源文档的排序获取最后一个文档数据。
hello> db.one.aggregate([{$group:{_id: '$id', co: {$sum: 1}}}])  # 分组后,必须有 _id 字段指定根据哪个字段分组。_id: '$id' 意思是根据id分组,然后统计每组的数量
[ { _id: 2, co: 2 }, { _id: 4, co: 1 }, { _id: 3, co: 1 } ]

hello> db.one.find().pretty()
[
  {
    _id: ObjectId("621ed6f91d216f37410dc108"),
    id: 2,
    name: 'woli',
    age: 9,
    sex: '男'
  },
  {
    _id: ObjectId("621ed7791d216f37410dc109"),
    id: 2,
    name: 'heol',
    age: 10,
    sex: '男'
  },
  {
    _id: ObjectId("621ed8411d216f37410dc10a"),
    id: 3,
    name: 'gana',
    age: 13,
    sex: '男'
  },
  {
    _id: ObjectId("621ed8411d216f37410dc10b"),
    id: 4,
    name: 'bala',
    age: 6,
    sex: '女'
  }
]
hello> db.one.aggregate([{$group: {_id: '$sex', max_age: {$max: '$age'} }}])  #  根据性别分组后,查找年龄最大的人
[ { _id: '女', max_age: 6 }, { _id: '男', max_age: 13 } ]

hello> db.one.aggregate([{$group: {_id: '$sex', age_list: {$push: '$age'} }}])  # $push 根据sex分组后,查看年龄列表
[
  { _id: '女', age_list: [ 6 ] },
  { _id: '男', age_list: [ 9, 10, 13 ] }
]

hello> db.one.aggregate([{$group: {_id: '$id', sex_list: {$addToSet: '$sex'}, name_lsit: {$push: '$name'} }}])
[
  { _id: 2, sex_list: [ '男' ], name_lsit: [ 'woli', 'heol' ] },
  { _id: 4, sex_list: [ '女' ], name_lsit: [ 'bala' ] },
  { _id: 3, sex_list: [ '男' ], name_lsit: [ 'gana' ] }
]

hello> db.one.aggregate( [{$match: {age: {$gt: 5, $lt: 9}}}, {$group: {_id: '$id', count: {$push: '$age'} } }] )  # 先使用 $match 将数据过滤后,在分组查询
[ { _id: 4, count: [ 6 ] } ]


# 正则表达式查找
# 正则表达式查找方式一:{filed: {$regex: 'patten'}}
hello> db.one.find({name: {$regex: 'w'}})
[
  {
    _id: ObjectId("621ed6f91d216f37410dc108"),
    id: 2,
    name: 'woli',
    age: 9,
    sex: '男'
  }
]
# 正则表达式查找方式二:{filed:/patten/}
hello> db.one.find({name:/w/})
[
  {
    _id: ObjectId("621ed6f91d216f37410dc108"),
    id: 2,
    name: 'woli',
    age: 9,
    sex: '男'
  }
]





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值