一. 增删查改
1. 增
(1.创建、连接数据库
use <database>
(2. 创建集合
db.createCollection("<collectionname>")
db.createCollection("<collectionname>",
{capped=true,autoIndexId=true,size=1024,max=100}
)
注:
capped #创建固定大小的集
autoIndexId #自动在_id字段创建索引
size #固定集合大小
max #最大文件数
(3. 创建文档(集合不存在自动创建)
db.<collection>.insertOne(
{ item: "canvas",
qty: 100,
tags: ["cotton"],
size: { h: 28, w: 35.5, uom: "cm" }
}
) #tags是数组,size是文档
db.<collection>.insertMany(
{ item: "journal", qty: 25, tags: ["blank", "red"], size: { h: 14, w: 21, uom: "cm" } },
{ item: "mat", qty: 85, tags: ["gray"], size: { h: 27.9, w: 35.5, uom: "cm" } },
{ item: "mousepad", qty: 25, tags: ["gel", "blue"], size: { h: 19, w: 22.85, uom: "cm" } })
db.collection.insert()#单一的,多元的都可以。
db.collection.save()
2.删
(1.删除数据库
db.dropDatabase() #删除当前数据库
(2. 删除集合
db.<collection>.drop() #删除指定数据库的所有集合
(3.删除文档
db.collection.deleteMany({ <field1>: <value1>, ... })
db.collection.deleteOne({ <field1>: { <operator1>: <value1> }, ... })
db.collection.remove()
3.查
db.collection.find({<query},{<projection>})
({ <field1>: <value1>, ... })
({ <array field>: { <operator1>: <value1>, ... } })
({"size.uom"="in"}) #嵌套字段使用点表示法
({ <field1>:{ <field1.1>:<value1.1>, ... }})#数组中嵌套了文档的查询
注:
query #查询条件
prohection #投影,表示哪些字段可以显示
AND = ,
OR = $or: [ , ]
$lt: < (less than )
$lte: <= (less than or equal to )
$gt: > (greater than)
$gte: >= (greater than or equal to)
$ne: !=
$all: 当且仅当
$elemMatch 可将一组条件限定到数组中单条文档的匹配上
4.改
db.collection.updateOne({<filter>}, {<update>}, <options>)
db.collection.updateMany({<filter>}, {<update>}, <options>)
db.collection.replaceOne({<filter>}, {<update>}, <options>)
filter #查询条件
update #替换对象以及替换的值
例如
db.inventory.updateOne(
{ item: "paper" }, #查询条件
{
$set: { "size.uom": "cm", status: "P" }, #修改对象以及替换的值
$currentDate: { lastModified: true } #
}
)
注:
$set:= $addFields: 向文档添加新字段。如果存在则被替换
$currentDate: 字段更新时间为当前日期,用来看啥时候给你更新的
$unset: 向文档中删除新字段
$addToSet:Adds elements to an array only if they do not already exist in the set.
$pop:Removes the first or last item of an array.
$pull:Removes all array elements that match a specified query.
$push:Adds an item to an array.
$:充当更新查询文档的第一个匹配项的占位符。
二.聚合+mapReduce
1.聚合
MongoDB中聚合(aggregate)主要用于处理数据(诸如统计平均值,求和等),并返回计算后的数据结果。聚合操作将多个文档的值分组在一起,并可以对分组数据执行各种操作以返回单个结果。
db.<collection>.aggregate()
注:
$match:# 按字段筛选文档,并将等于的文档传递到下一阶段。
$group: #按字段对文档进行分组,以计算每个唯一的量总和
2.mapReduce
参考文档地址:https://docs.mongodb.com/manual/reference/operator/update/positional/(强烈推荐)
本文还有很多没有陈列出来,没有什么比官方文档更加详细的了,而且文档还给了我们shell来运行,太方便了。