Mongoldb 常用命令

Mongodb Mongo 介绍

Mongod 是处理 MengoDB 系统的主要进程。主要负责处理数据请求,管理数据存储,和执行后台管理操作。当我们运行 mongod 命令意味着正在启动 MongoDB 进程,并且在后台运行。

mongo 是一个命令行实现的客户端操作 mongodb 的工具,用于连接一个特定的 mongod 实例。当我们没有带参数运行 mongo 命令它将使用默认的端口号 27017 和 localhost 进行连接

常用命令

exit 		# 退出
mongo --version		# 查看命令
> help
    db.help()                    help on db methods						# 查看操作数据库方法
    db.mycoll.help()             help on collection methods		# 查看集合的操作方法
    sh.help()                    sharding helpers							# 分片
    rs.help()                    replica set helpers					# 复制集
    help admin                   administrative help					# admin 帮助
    help connect                 connecting to a db help			# 查看链接
    help keys                    key shortcuts								# 健的结构
    help misc                    misc things to know
    help mr                      mapreduce

    show dbs                     show database names					# 查看所有的数据库
    show collections             show collections in current database			# 查看当前数据库所有的数据集
    show users                   show users in current database			# 查看当前数据库所有的管理员
    show profile                 show most recent system.profile entries with time >= 1ms
    show logs                    show the accessible logger names		# 查看全部日志
    show log [name]              prints out the last segment of log in memory, 'global' is default
    use <db_name>                set current database			# 切换数据库
    db.foo.find()                list objects in collection foo		# 列出当前指定结合下的所有文档
    db.foo.find( { a : 1 } )     list objects in foo where a == 1	# 按条件查询指定集合下所有的文档
    it                           result of the last line evaluated; use to further iterate	# 修改查询数据返回结果的模式
    DBQuery.shellBatchSize = x   set default number of items to display on shell	# 修改返回结果的单页数据量,默认20条
    exit                         quit the mongo shell
// 查看数据库版本
> db.version()
4.2.6

// 查看当前数据库
> db
admin
> db.getName()
admin

// 查看所有的数据库
> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB

// 查看数据库状态
> db.stats()

// 查看当前连接
> db.getMongo()
connection to 127.0.0.1:27017

// 远程连接,指定 admin 库
mongo ip/admin

2. 库和表
    // 建库, 没有默认创建,没有数据的时候,是一个虚拟库
    > use test
    switched to db test
    
    // 删除
    > db.dropDatabase()
    { "ok" : 1 }
    
    // 创建集合(表)
    方法一:
    > use app
  switched to db app
  > db.createCollection('a')	// 创建一个空表
  { "ok" : 1 }
  > db.createCollection('b')
  { "ok" : 1 }


  方法二:
  当插入一个文档的时候,一个集合就会自动创建
  > use app
  switched to db app
  > db.c.insert({username: "mongodb"})		// 直接插入c表中数据
  WriteResult({ "nInserted" : 1 })
  > db.c.find()
  { "_id" : ObjectId("630c66cb7297c0ea8ac76062"), "username" : "mongodb" }

  // 删除集合
  > show tables;
  c
  > db.c.drop()
  true

  // 重命名
  > show tables;
  c
  > db.c.renameCollection("b")
  { "ok" : 1 }
  > show tables;
  b


insert 插入

语法:
db.<集合>.insertOne(<json对象>)
db.<集合>.insertMany([<JSON 1], <json 2>, ....<json n>])

示例:
> db.fruit.insertOne({name: "apple"})
{
    "acknowledged" : true,
    "insertedId" : ObjectId("630c776c7297c0ea8ac76064")
}


> db.fruit.insertMany([
... {name: "aaa"},
... {name: "bbb"},
... {name: "ccc"}
... ])
{
    "acknowledged" : true,
    "insertedIds" : [
    	ObjectId("630c78b07297c0ea8ac76065"),
    	ObjectId("630c78b07297c0ea8ac76066"),
    	ObjectId("630c78b07297c0ea8ac76067")
    ]
}

> db.fruit.find()		// 查看

批量插入:
for(i=0; i<1000; i++){ db.log.insert({"uid": i, "name": "mongodb", "age": 6, "data": new Date()}); }

find 查找

#关于 find:
find 是 MongoDB 中查询数据的基本指令,相当于 SQL 中的 SELECT。find 返回的是游标。

#find 示例:
db.movies.find({"year”:1975}) //单条件查询

db。movies.find(f"year":1989, "title": "Batman"})		//多条件 and查询

db.movies.find({ $and: [{"title": "Batman"}, {"category":"action"}]})		//and 的另 一种形式

db.movies.find({ $or: [{"year":1989}, {"tit1e": "Batman"}] }) 	//多条件or 查询 
db.movies.find({"title": /^B/ }) //按正则表达式查找

查询条件对照表

SQL MQL
a=1 {a: 1}
a<>1 {a:{$ne:1}}
a>1 {a:{$gt:1}}
a>=1 {a:{$gte: 1}}
a<1 {a:{$lt:1}}
a<=1 {a:{$lte:1}}

查询逻辑对照表

SQL MQL
a=1 AND b=1 {a:1, b:1} 或 {$and:[{a:1},{b:1}]}
a=1 OR b=1 {$or:[{a:1},{b:1}]}
a IS NULL {a:{$exists: false}}
a IN (1,2,3) {a: {$in:[1,2,3]}}

查询逻辑运算符

$lt:存在并小于 
$lte:存在并小于等于 
$gt:存在并大于 
$gte:存在并大于等于 
$ne:不存在或存在但不等于 
$in:存在并在指定数组中 
$nin:不存在或不在指定数组中 
$or:匹配两个或多个条件中的一个 
$and:匹配全部条件

使用find搜索子文档

find 支持使用 "field.sub_field" 的形式查询子文档,假设有一个文档:
db.fruit.insertOne({
name:"apple",
from: {
country: "china",
province: "guangdong"
}
})

正确写法:
db.fruit.find({ "from.country": "china" })

使用find 搜索数组

find 支持对数组中的元素进行搜索,假设有一个文档
db.fruit.insert([
{"name": "apple", color: ["red", "green"]},
{"name": "mango", color: ["yellow", "green"]}
])

查看单个条件:
db.fruit.find({color: "red"})
查询多个条件
db.fruit.find({ $or: [{color: "red"}, {color: "yellow"}]} )

搜索数组中的对象

考虑以下文档,在其中搜索 
db.movies.insertOne ( {
"title" "Raiders of the Lost Ark", 
"filming_locations": [
{"city": "Los Angeles", "state": "CA", "country": "USA"}, 
{"city": "Rome", "state": "Lazio", "country": "Italy"}, 
{"city": "Florence", "state": "sc", "country": "USA"} 
]
})

//查找城市是 Rome 的记录
db.movies.find({"filming_locations.city": "Rome"})

控制 find 返回字段

find 可以指定只返回指定的字段
_id	字段必须明确指明不反悔,否则默认返回;
在 MongoDB 中我们称这为投影
db.movies.find({}, {"_id":0, title:1})		// 只显示 title 不显示 _id;

remove 删除文档

Remove 命令需要配合查询条件使用;
匹配查询条件的的文档会被删除;
指定一个空文档条件会删除所有文档;

以下示例:
db.testcol.remove({a:1}) 	//删除 a 等于 1 的记录

db.testcol.remove({a: {slt:5}}) //删除 a 小于 5 的记录 
db.testcol.temove({}) 	//删除所有记录 
db.testcol.remove () //报错