文章目录
具体详细操作参考 官方操作文档
一、数据库
显示所有的数据库:show dbs、show databases
显示当前所在的数据库:db
选择和创建数据库:use 数据库名称
删除当前数据库:db.dropDatabase()
基础数据库介绍
admin :从权限的角度来看,这是"root"数据库。要是将一个用户添加到这个数据库,这个用户自动继承所有数据库的权限
local:这个数据永远不会被复制,可以用来存储限于本地单台服务器的任意集合
config:当Mongo用于分片设置时,config数据库在内部使用,用于保存分片的相关信息
二、集合
1、新增集合
显示新增:db.createCollection(name)
隐式新增:通过插入文档数据来默认创建,db.collection.insert({id:1,name:forlan});
test> db.createCollection("forlan1")
{ ok: 1 }
test> db.forlan2.insert({id:1,name:"forlan"});
DeprecationWarning: Collection.insert() is deprecated. Use insertOne, insertMany, or bulkWrite.
{
acknowledged: true,
insertedIds: { '0': ObjectId("64a67bcf918d27194254b6a9") }
}
命名规范
不能是空字符串
不能含有 \0字符(空字符),这个字符表示集合名的结尾
不能以 "system."开头,这是为系统集合保留的前缀
不能含有保留字符。另外千万不要在名字里出现$
2、查看集合
显示数据库中所有的集合:show tables、show collections
test> show tables;
forlan1
forlan2
3、删除集合
删除当前集合:db.collection.drop()
清空一个集合(效率低,直接删集合更快):db.collection.remove({})
test> db.forlan1.drop()
true
三、文档
mongo _id的生成规则: 时间戳+机器码+PID+计数器
1、新增文档
语法:
db.collection.insert():单文档插入
db.collection.insertMany():多文档插入
db.collection.insert():单、多文档插入
例子:
db.collection.insert({k1:v1,k2:v2})
test> db.forlanC.insertOne({uid:1,name:"forlan1",city:"广州",age:25})
{
acknowledged: true,
insertedId: ObjectId("64a4ef4475b1d2bd73f082e1")
}
db.collection.insertMany([{k1:v1,k2:v2},{k1:v1,k2:v2}])
test> db.forlanC.insertMany([{uid:2,name:"forlan2",city:"深圳",age:27},{uid:3,name:"forlan3",city:"佛山",age:30}])
{
acknowledged: true,
insertedIds: {
'0': ObjectId("64a4ef4c75b1d2bd73f082e2"),
'1': ObjectId("64a4ef4c75b1d2bd73f082e3")
}
}
db.collection.insert([{k1:v1,k2:v2}…])
test> db.forlanC.insert({uid:1,name:"forlan1",city:"广州",age:25})
DeprecationWarning: Collection.insert() is deprecated. Use insertOne, insertMany, or bulkWrite.
{
acknowledged: true,
insertedIds: { '0': ObjectId("64a4efce75b1d2bd73f082e4") }
}
test> db.forlanC.insert([{uid:2,name:"forlan2",city:"深圳",age:27},{uid:3,name:"forlan3",city:"佛山",age:30}])
{
acknowledged: true,
insertedIds: {
'0': ObjectId("64a4efe075b1d2bd73f082e5"),
'1': ObjectId("64a4efe075b1d2bd73f082e6")
}
}
2、更新文档
语法:
db.collection.updateOne(filter, update, options):修改集合中的一个现有文档
db.collection.updateMany(filter, update, options):修改集合中的多个现有文档
db.collection.replaceOne(filter, replacement, options):替换集合中的一个现有文档
db.collection.update(query, update, options):修改或替换集合中的一个或多个现有文档,已弃用
例子:
db.collection.updateOne(条件,更新字段),更新匹配的第一个文档
test> db.forlanC.updateOne({name:"forlan1"},{'$set':{age:26,id:1}});
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0
}
db.collection.updateMany(条件,更新字段),更新所有匹配的文档
test> db.forlanC.updateMany({age:27},{'$set':{id:27}});
{
acknowledged: true,
insertedId: null,
matchedCount: 2,
modifiedCount: 1,
upsertedCount: 0
}
db.collection.replaceOne(条件,替换内容),替换匹配的第一个
test> db.forlanC.replaceOne({name:"forlan1"},{id:1})
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0
}
db.collection.update(条件,更新字段),更新匹配文档,不加{multi:true},就相当于updateOne
test> db.forlanC.update({age:27},{'$set':{id:28}},{multi:true});
{
acknowledged: true,
insertedId: null,
matchedCount: 2,
modifiedCount: 1,
upsertedCount: 0
}
3、删除文档
语法:
db.collection.deleteOne(filter, options):删除集合中的一个现有文档
db.collection.deleteMany(filter, options):删除集合中的多个现有文档
db.collection.remove(query, options):删除集合中的一个或多个现有文档
例子:
deleteOne删除uid=2的文档
test> db.forlanC.deleteOne({uid:2})
{ acknowledged: true, deletedCount: 1 }
deleteMany删除uid<=3的文档
test> db.forlanC.deleteMany({uid:{$lte:3}})
{ acknowledged: true, deletedCount: 3 }
deleteMany删除所有文档
test> db.forlanC.deleteMany({})
{ acknowledged: true, deletedCount: 3 }
remove删除uid=1的文档,已弃用,会提示
test> db.forlanC.remove({uid:1})
DeprecationWarning: Collection.remove() is deprecated. Use deleteOne, deleteMany, findOneAndDelete, or bulkWrite.
{ acknowledged: true, deletedCount: 1 }
4、查询文档
4.1 统计
语法:
db.collection.count(query, options):统计
例子:
统计uid=1的文档数
test> db.forlanC.count({uid:1})
1
4.2 分页、排序
db.collection.find().skip(NUMBER).limit(NUMBER):分页查询,使用skip()方法来跳过指定数量的数据,limit()方法来读取指定数量的数据,
db.forlanC.find().skip(0).limit(5) // 第一页,每页显示5个
db.forlanC.find().skip(5).limit(5) // 第二页,每页显示5个
db.forlanC.find().skip(10).limit(5) // 第三页,每页显示5个
db.collection.find().sort({field:NUMBER}) :排序,1升序、-1降序
skip(), limit(), sort()三个放在一起执行的时候,执行的顺序是先 sort(), 然后是 skip(),最后是显示的 limit(),和命令编写顺序无关
4.3 查询
语法:
db.collection.find(query, [projection], options):查询
db.collection.find({},{field1:1,field2:1…}):查询显示特定字段
db.collection.find({字段:/正则表达式/}) :正则表达式是 js的语法
db.collection.find({field:{$in: [value1,value2]}}):包含
db.collection.find($and:[ {field1:value1}…]):条件
db.collection.find({field1: { operator1: value1 }, … }):比较
- db.collection.find({ “field” : { $gt: value }}):大于: field >value
- db.collection.find({ “field” : { $lt: value }}):小于: field < value
- db.collection.find({ “field” : { $gte: value }}) :大于等于: field >= value
- db.collection.find({ “field” : { $lte: value }}):小于等于: field <= value
- db.collection.find({ “field” : { $ne: value }}):不等于: field != value
例子:
查找uid=1的文档
test> db.forlanC.find({uid:1})
[
{
_id: ObjectId("64a4f8f475b1d2bd73f082f3"),
uid: 1,
name: 'forlan1',
city: '广州',
age: 25
}
]
查找以name是以forlan开头的文档
test> db.forlanC.find({name:/^forlan*/})
[
{
_id: ObjectId("64a686e8918d27194254b6b6"),
uid: 1,
name: 'forlan1',
city: '广州',
age: 25
},
{
_id: ObjectId("64a686e8918d27194254b6b7"),
uid: 2,
name: 'forlan1',
city: '深圳',
age: 27
},
{
_id: ObjectId("64a686e8918d27194254b6b8"),
uid: 3,
name: 'forlan3',
city: '佛山',
age: 30
}
]
查找uid=1,同时name=forlan1的文档
test> db.forlanC.find({$and:[{uid:1},{name:"forlan1"}]})
[
{
_id: ObjectId("64a4f8f475b1d2bd73f082f3"),
uid: 1,
name: 'forlan1',
city: '广州',
age: 25
}
]
查找指定字段uid和name
test> db.forlanC.find({},{uid:1,name:1});
[
{
_id: ObjectId("64a6931c918d27194254b6bc"),
uid: 1,
name: 'forlan1'
},
{
_id: ObjectId("64a6931c918d27194254b6bd"),
uid: 2,
name: 'forlan2'
},
{
_id: ObjectId("64a6931c918d27194254b6be"),
uid: 3,
name: 'forlan3'
}
]
四、索引
1、介绍
索引主要是帮助MongoDB高效获取数据的数据结构
如果没有索引,MongoDB必须执行全集合扫描,即扫描集合中的每个文档,以选择与查询语句匹配的文档。这种扫描全集合的查询效率是非常低的,特别在处理大量的数据时,查询可能要花费几十秒甚至几分钟,这对网站的性能是非常致命的
MongoDB索引使用B树数据结构(确切的说是B-Tree,MySQL是B+Tree),多叉树
2、类型
- 单字段索引:对文档单个字段创建索引
- 复合索引:对文档多个字段创建索引
3、管理操作
3.1 创建索引
语法:db.collection.createIndex(keys, options, commitQuorum)
例子:
创建单索引,按uid字段升序
test> db.forlanC.createIndex({uid:1})
uid_1
创建复合索引,按uid字段降序,name散列
test> db.forlanC.createIndex({uid:-1,name:"hashed"})
uid_-1_name_hashed
3.2 查看索引
语法:db.collection.getIndexes()
test> db.forlanC.getIndexes()
[
{ v: 2, key: { _id: 1 }, name: '_id_' },
{ v: 2, key: { uid: 1 }, name: 'uid_1' },
{
v: 2,
key: { uid: -1, name: 'hashed' },
name: 'uid_-1_name_hashed'
}
]
3.3 删除索引
删除指定索引
- 使用索引名称删除:db.collection.dropIndex(indexName)
- 使用索引文档删除:db.collection.dropIndex({field:value})
test> db.forlanC.dropIndex("uid_-1_name_hashed")
{ nIndexesWas: 3, ok: 1 }
test> db.forlanC.dropIndex({uid: 1 })
{ nIndexesWas: 2, ok: 1 }
删除所有索引,处理主键索引_id:db.collection.dropIndexes()
test> db.forlanC.dropIndexes()
{
nIndexesWas: 3,
msg: 'non-_id indexes dropped for collection',
ok: 1
}