Skip to content

基本操作

webdes
mongodb增删改查
  • show dbs 打印服务器上所有数据库的列表。
  • use <db> 将当前数据库切换到<db>。该 mongoshell 变量 db 被设置为当前数据库。
  • show collections 打印当前数据库的所有集合的列表。
  • show users 打印当前数据库的用户列表。
  • show roles 打印用于当前数据库的用户定义和内置的所有角色的列表。
  • show profile 打印需要 1 毫秒或更多的五个最近的操作。有关详细信息,请参阅数据库分析器上的文档。
  • show databases 打印所有可用数据库的列表。
sh
# 查看所有数据库
show dbs;   
show databases;

# 查看当前在哪个库
db

# 切换数据库
use test-database

#查看库下的集合,等于show tables
show collections

# 查看集合信息
db.[collections].stats()

# 删除数据库,当初当前数据库。
db.dropDatabase()

写入

插入文档-插入方法

MongoDB提供了将文档插入到集合中的以下方法:

  1. db.collection.insertOne() 将单个文档插入到集合中。
  2. db.collection.insertMany() 将多个 文档插入到集合中。
  3. db.collection.insert() 将单个文档或多个文档插入到集合中。
  4. db.collection.save() 根据文档参数更新现有文档或插入新文档
sh
# **key加不加引号都可以**

#insert one
#格式 db.collection.insertOne(documents)
db.accounts.insertOne({
		"_id": "account1"  # 有这个_id则使用这个id,没有系统自动创建insertedId
    "name": "Json.CN",
    "url": "http://www.json.cn",
})

{
  acknowledged: true, # 安全写级别启用
  insertedId: ObjectId('67a225043d1bc89530a91d3b')
}

#insertMany
db.user_info.insertMany(
  [
    {name:"yuchao",age:"28",website:"www.yuchaoit.cn"},
    {name:"sanpang",age:"29"},
    {name:"ergou",addr:"北京"},
  ]
)

#generate ObjectId
ObjectId()

#根据对象主键获取时间
ObjectId('67a230e05942619cf1290332').getTimestamp()
2025-02-04T15:23:12.000Z

查询文档

简单查询

sh
#获取所有表内数据
db.[collections].find()
db.[collections].find().pretty() #易读的方式来读取数据

# 复合主键查询,查询主键中银行账户类型为储蓄账户的文档
db.[collections].find({"_id.type": "savings"})
{"_id": "accountNo": "001", "type": "savings","name": "irene", "balance": 80}

#查询单条SQL, select * from user_info limit 1;
db.user_info.findOne()

#按条件查询,select * from user_info where name='yuchao';
db.user_info.find({age:"28"})

# 查询出文档的部分字段 select name,age from user_info where name='yuchao';
db.user_info.find({name:"yuchao"},{name:1,age:1})

# 去掉主键显示 ,以及单独显示某字段
# 单独去掉某个字段,就显示剩余字段
# 语法 find({条件1,条件2},{字段:1或0})
db.user_info.find({name:"yuchao"},{name:1,_id:0})
{ "name" : "yuchao" }
{ "name" : "yuchao" }

db.user_info.find({name:"yuchao"},{_id:0})
{ "name" : "yuchao", "website" : "www.yuchaoit.cn" }
{ "name" : "yuchao", "age" : "28", "website" : "www.yuchaoit.cn" }

db.user_info.find({name:"yuchao"},{age:0})
{ "_id" : ObjectId("634a8d38d2a83b89e17c732e"), "name" : "yuchao", "website" : "www.yuchaoit.cn" }
{ "_id" : ObjectId("634b7cfed2a83b89e17c7333"), "name" : "yuchao", "website" : "www.yuchaoit.cn" }

嵌套查询

嵌套查询

sh
db.inventory.find({"size.h":22.85})
{ "_id" : ObjectId("634b8f91d2a83b89e17c7339"), "item" : "planner", "qty" : 75, "size" : { "h" : 22.85, "w" : 30, "uom" : "cm" }, "status" : "D" }

db.inventory.find({"size.h":22.85},{"status":1,item:1})

db.inventory.find({"size.h":22.85},{"status":1,item:1,_id:0})

逻辑查询

逻辑查询

比较运算符

  • $eq 匹配等于指定值的值。
  • $gt 匹配大于指定值的值。
  • $gte 匹配大于或等于指定值的值。
  • $in 匹配数组中指定的任何值。
  • $lt 匹配小于指定值的值。
  • $lte 匹配小于或等于指定值的值。
  • $ne 匹配不等于指定值的所有值。
  • $nin不匹配数组中指定的值。

逻辑查询运算符

  • $and 使用逻辑连接查询子句AND返回与两个子句的条件相匹配的所有文档。
  • $not 反转查询表达式的效果,并返回与查询表达式不匹配的文档。
  • $nor 使用逻辑连接查询子句NOR返回所有无法匹配两个子句的文档。
  • $or 使用逻辑连接查询子句OR返回与任一子句的条件相匹配的所有文档
  • $exists 包含某个字段的文档返回,可以联合查询,返回更加准确的结果,因为有些查询字段不存在,就会使得有些不相等的查询返回
  • $type 返回键是特定类型的文档
sh
# and语句
select * from inventory where status="A" and qty< 30;

db.inventory.find(
{"status":"A","qty":{$lt:30}}
)

# and 案例2
# select * from inventory where status='A' AND size.uom='cm';

db.inventory.find(
{"status":"A","size.uom":{$eq:"cm"}}
)

# 或者
db.inventory.find(
{"status":"A","size.uom":"cm"}
)

# or 逻辑查询
select * from inventory where status=A or qty<30;

db.inventory.find(
 {
   $or:[
     {qty:{$lt:30}},
     {"status":"A"}
   ]
 }
)
{ "_id" : ObjectId("634b8f91d2a83b89e17c7336"), "item" : "journal", "qty" : 25, "size" : { "h" : 14, "w" : 21, "uom" : "cm" }, "status" : "A" }
{ "_id" : ObjectId("634b8f91d2a83b89e17c7337"), "item" : "notebook", "qty" : 50, "size" : { "h" : 8.5, "w" : 11, "uom" : "in" }, "status" : "A" }
{ "_id" : ObjectId("634b8f91d2a83b89e17c733a"), "item" : "postcard", "qty" : 45, "size" : { "h" : 10, "w" : 15.25, "uom" : "cm" }, "status" : "A" }
> 


# or 逻辑运算2
# 查询status是A或D的文档

db.inventory.find( 
 {
 		status: {$in:["A","D"]}
 }
)
{ "_id" : ObjectId("634b8f91d2a83b89e17c7336"), "item" : "journal", "qty" : 25, "size" : { "h" : 14, "w" : 21, "uom" : "cm" }, "status" : "A" }
{ "_id" : ObjectId("634b8f91d2a83b89e17c7337"), "item" : "notebook", "qty" : 50, "size" : { "h" : 8.5, "w" : 11, "uom" : "in" }, "status" : "A" }
{ "_id" : ObjectId("634b8f91d2a83b89e17c7338"), "item" : "paper", "qty" : 100, "size" : { "h" : 8.5, "w" : 11, "uom" : "in" }, "status" : "D" }
{ "_id" : ObjectId("634b8f91d2a83b89e17c7339"), "item" : "planner", "qty" : 75, "size" : { "h" : 22.85, "w" : 30, "uom" : "cm" }, "status" : "D" }
{ "_id" : ObjectId("634b8f91d2a83b89e17c733a"), "item" : "postcard", "qty" : 45, "size" : { "h" : 10, "w" : 15.25, "uom" : "cm" }, "status" : "A" }


# in 逻辑运算
db.inventory.find( { qty: { $in: [ 10, 25 ] } } )
{ "_id" : ObjectId("634b8f91d2a83b89e17c7336"), "item" : "journal", "qty" : 25, "size" : { "h" : 14, "w" : 21, "uom" : "cm" }, "status" : "A" }

# 逻辑查询 结合正则表达式
# 这些语句,都是为了查数据么,找规则提取数据
# 提取qty小于30,或者是item以p开头

db.inventory.find( {
 status: "A",
 $or: [ { qty: { $lt: 30 } }, { item: /^p/ } ]
} )
{ "_id" : ObjectId("634b8f91d2a83b89e17c7336"), "item" : "journal", "qty" : 25, "size" : { "h" : 14, "w" : 21, "uom" : "cm" }, "status" : "A" }
{ "_id" : ObjectId("634b8f91d2a83b89e17c733a"), "item" : "postcard", "qty" : 45, "size" : { "h" : 10, "w" : 15.25, "uom" : "cm" }, "status" : "A" }


# 结果再限制字段
db.inventory.find( {  status: "A",  $or: [  { qty: { $lt: 30 } },  { item: /^p/ }   ]  },{     _id:0, status:1, qty:1, item:1 } )
{ "item" : "journal", "qty" : 25, "status" : "A" }
{ "item" : "postcard", "qty" : 45, "status" : "A" }

# exist
db.accounts.find({"_id.type": {$ne: "checking", $exists: true}})

# type 返回BSON类型的文档 objectId object null string或者序号,2代表字符串。如返回主键是字符串类型的文档
db.accounts.find({"_id": { $type: "string"}})

数组操作符

  • $all 要求数组中所有值都需要包含在查询数组中。
  • $elemMatch 要求查询数组中有任一值满足elemMatch筛选条件即可。

运算操作费

$regex 正则。

sh
# {<field>: {: /pattern/,: '<options>'}}
# {<field>: {: /pattern/<options>}}

db.accounts.find({name: {$in: [/^c/, /^j/]}})

db.accounts.find({name: {$regex: /LIX/, $options: 'i'}})

游标

游标函数

  • cursor.hasNext()
  • cursor.next()
  • cursor.forEach()
  • cursor.limit()
  • cursor.skip()
  • cursor.count()
  • cursor.sort()
js
// 默认返回20条数据,游标存在十分钟,十分钟后消失,重置
var myCursor = db.accounts.find();

//可以使用noCursonTimeout(),使游标保持
var myCursor = db.accounts.find().noCursonTimeout();

//主动关闭游标
MyCursor.close()

skip函数永远在limit前执行

文档投影

除了主键,其它字段只能是包含或者不包含,不能混用。

$slide

sh
db.accounts.find({}, {_id:0,name: 1, contact: {$slide: 1}}) # 返回数组第一个值
db.accounts.find({}, {_id:0,name: 1, contact: {$slide: -1}}) # 返回数组最后一个值
db.accounts.find({}, {_id:0,name: 1, contact: {$slide: [1,2]}) # 返回数组跳过一个,取两个

db.accounts.find({contact: {$gt: "alabama"}, {_id:0,name: 1, contact.$: 1) # 使用find里的筛选条件

更新文档

更新文档

基本方法

  • db.collection.update()即使可能有多个文档通过过滤条件匹配到,但是也最多也只更新或者替换一个文档。

  • db.collection.updateOne(<filter>,<update>, <options>)即使可能有多个文档通过过滤条件匹配到,但是也最多也只更新一个文档

  • db.collection.updateMany(<filter>, <update>, <options>) 更新所有通过过滤条件匹配到的文档

  • db.collection.replaceOne(<filter>, <replacement>, <options>) 即使可能有多个文档通过过滤条件匹配到,但是也最多也只替换一个文档

$currentDate 操作符具有如下形式:

sh
{ $currentDate: { <field1>: <typeSpecification1>, ... } }

操作符

  • $set:更新或者添加字段
  • $unset: 删除文档特定字段
  • $rename: 重命名字段
  • $inc: 增加减少
  • $mul: 乘
  • $min 保留小值,不只是数字
  • $max 保留大值,不只是数字
sh
db.inventory.update(
 	 {"item":"paper"},
   {
     $set:{"size.uom":"cm",status:"P"},
     $currentDate:{lastModified:true}
   }
)
 
db.inventory.update(
 	 {"item":"paper"},
   {
     $unset:{"size.uom":"",status:""} #值是多少没有影响
   }
)
类型比较

最小->最大

  • Null
  • Numbers
  • Symbol, String
  • Object
  • Array
  • Bindata
  • ObjectId
  • Boolean
  • Date
  • Timestamp
  • Regular Expression

数组更新操作符

操作符

$占位符

更新单个
sh
{
		name:"lawrence",
		newArray: [
			"push2",
			"push1",
			"pop2",
			"pop1",
		]
}

db.accounts.update(
	{
		name:"lawrence",
		newArray: "pop2"
	},
	{
		$set:{
			"newArray.$":"update" 
		}
	}
)

{
		name:"lawrence",
		newArray: [
			"push2",
			"push1"
			"update"
			"pop1"
		]
}
更新所有
sh
{
		name:"lawrence",
		newArray: [
			"push2",
			"push1",
			"pop2",
			"pop1"
		]
}

db.accounts.update(
	{
		name:"lawrence"
	},
	{
		$set:{
			"newArray.$[]":"update" 
		}
	}
)

{
		name:"lawrence",
		newArray: [
			"update",
			"update"
			"update"
			"update"
		]
}

删除文档

删除文档

方法

  • db.collection.remove() 删除单个文档或与指定过滤器匹配的所有文档。 参数{},清空集合
  • db.collection.drop()此方法获取受影响的数据库上的写入锁定,并将阻止其他操作,直到 其完成。 不加参数删除所有数据包括索引
  • db.collection.deleteOne() 最多删除与指定过滤器匹配的单个文档,即使多个文档可能与指定的过滤器匹配。
  • db.collection.deleteMany() 删除与指定过滤器匹配的所有文档。
sh
db.accounts