mongoDB基础
基础CRUD
Update
-
insert
-
_id是每条记录的必填字段,不一定是ObjectId类型。默认使用ObjectId类型以确保_id不重复
-
db.name.insert({}) db.name.insert([{},{}])
-
db.name.insert([{},{}], "ordered":false)
- ordered=true 一条记录插入失败,后面的记录不会插入
- ordered=false 一条记录插入失败后,后面的插入操作还会继续
-
-
update
-
db.Name.updateMany({"city":"HUDSON"}, {"$inc": {"pop": 10}})
-
set $push(string, number, boolean)
-
$push
- array追加元素
- 将字段转化为array
-
all operators:https://docs.mongodb.com/manual/reference/operator/update/#id1
-
-
db.Name.updateOne()
-
-
delete
- db.Name.deleteOne() db.Name.deleteMany()
- db.name.drop() 删除collection
- 删除一个database下的所有collection时,也会删掉database
-
upsert
- 默认为false
- db.name.updateMany({"field":value}, {"$set":{"field2":value2}}, {"upsert":true})
Find
-
db.FindOne() db.FindOne({})
-
comparison operators
- ne lt lte $regex
-
logic operators
-
or not
-
nor":[{"field1:1"}, {"field2":2}])
-
$not : negate the query requirement 后面只跟一个匹配条件
- db.name.find({"field1":{"$not":{"eq":"123"}}}) 正确
- db.name.find({"$not":{"field1":"123"}}) 错误
-
-
expression operators
-
$expr
- 作用:在同一个文档内做比较
-
-
projection
- 指定返回的结果包含哪些字段,不包含哪些字段
- db.name.find({"field":value}, {"filed2":1})
- projection中只能使用全0或全1,除非想返回某些字段但不想返回_id
-
$elemMatch
- 数组中元素匹配
-
dot notation
- db.name.find("field1.field2":value)
- db.name.find({"array1.0.field1":value})
-
sort & limit
-
db.name.find().sort({"field":1}).limit(1)
- sort({"pop":1}) 升序
- sort({"pop":-1}) 降序
-
-
index
-
createIndex{"field":1}
- 1表示升序,-1表示降序
-
import/export
- mongodump
mongoexport
mongorestore
mongoimport
aggregation framework
-
db.name.aggregate
- aggregate中的语句会顺序执行 pipeline
-
stages:group $project
concept
$
-
代表操作符
-
代表取字段的值
- {"eq"["end station id"]:}}
syntax
-
MQL syntax
- {"field":{operator:value}}
-
aggregation syntax
- {operator:{"field":value}}
cursor method
- pretty() count() sort() limit()
- cursor.limit().sort() means cursor.sort().limit()
- 排序时,null值被认为是最小值
ACID
concern
-
write conern
- one(数据被写入1台server)
- majority
-
read concern
- local (default)
- majority
-
read preference(从哪里读)
- primary
- nearest
- certain node
model methodology
- workload description 列出可能的查询,每个查询的速度要求
- decide relationship: embedding/reference
- schema design patterns 选择模型的设计模式
validation
- 子主题 1
atlas界面操作
在文档中插入记录
其他备注
密码:m001-mongodb-basics
cases
example1
- {"amenities":["shampoo"]} 查找字段是array且只包含"shampoo"的记录
- {"amenities":["shampoo", "wifi"]} 查找的结果与数组中元素的顺序有关
- {"amenities":{"$all":["shampoo", "wifi"]}} 查找字段是数组且至少包含shampoo和wifi的记录,不管元素的排序
- {"amenities":{"$size":20}} 指定数组的长度
example2
- db.name.aggregate([{"group":{"_id":"sum":1}}}])
- db.name.aggregate([{"group":{"_id":"sum":"$price"}}}])
XMind - Trial Version
网友评论