很早之前的笔记,同步一下
官方地址
use cool
# 等价于mysql drop table user
db.user.drop()
find() 方法查找多条,findOne() 查找一条
# 等价于mysql select * from user
db.user.find()
# 等价mysql select * from user where name = 'xie'
db.user.find({"name":"xie"})
# 等价于mysql select * from user where name = 'xie' and age = 25
db.user.find({"name":"xie","age":25})
# 等价mysql select * from user where age in (25,33)
db.user.find({"age":{$in:[25,33]}})
# 等价mysql select * from user where age = 25 or age = 33
db.user.find({$or:[{age:25},{age:33}]})
# 等价mysql select * from user where age = 25 and (name in ("rui","lucky") or weight = 90)
db.user.find( {age:25, $or:[ {name:{$in:["rui","lucky"]}}, {"info.weight":90}]})
# 等价mysql select * from user where (age = 25 and name = "xie") or (age = 50 or name = "rui" )
db.user.find({$or:[ {age:25,name:"xie"}, {age:50,name:"rui"} ]})
# 等价于mysql select * from user where name like "%i%"
db.user.find({name:/i/})
# 等价mysql select * from user where name like "x%"
db.user.find({name:/^x/})
# 等价于mysql select * from user where name like "%g"
db.user.find({name:/g$/})
# 等价于 mysql select * from user where age > 25
db.user.find({age:{$gt:25}})
# 等价于 mysql select * from user where age >= 25
db.user.find({age:{$gte:25}})
# 等价于 mysql select * from user where age < 55
db.user.find({age:{$lt:55}})
# 等价于 mysql select * from user where age <= 55
db.user.find({age:{$lte:55}})
# 等价于 mysql insert(`name`,`age`,`info`) value ('xie',25,'{"height":183,"weight":90"}')
db.user.insert({name:"xie",age:25,info:{height:183,weight:90}})
#等价于 insert user (`name`,`age`,`info`) values
#('xie',25,'{"height":183,"weight":90}'),
#('rui',50,'{"height":180,"weight":85}'),
#('xiang',33,'{"height":175,"weight":80}'),
#('goods',55,'{"height":170,"weight":90}'),
#('lucky',45,'{"height":165,"weight":70}');
db.user.insertMany([
{ name: "xie", age: 25, info: { height: 183, weight: 90, }},
{ name: "rui", age: 50, info: { height: 180, weight: 85}},
{ name: "xiang", age: 33, info: { height: 175, weight: 80}},
{ name: "goods", age: 55, info: { height: 170, weight: 90}},
{ name: "lucky", age: 45, info: { height: 165, weight: 70}}
])
# 等价于 mysql update user set name = "update after" where age = 25 limit 1
db.user.updateOne({age:25},{$set:{name:"update after"}})
# 等价于 mysql update user set name = "update after" where age = 25
db.user.updateMany({age:25},{$set:{name:"update after"}})
# 等价于 mysql delete from user where age = 25 limit 1
db.user.deleteOne({age:25})
# 等价于 mysql delete from user where age = 25
db.user.deleteMany({age:25})
# 查找一个,找到就修改
# 由于设置upsert:true 找不到会创建数据
# 由于设置returnNewDocument:true 如果数据不存在,且upsert:true,则返回新创建的数据内容
db.user.findOneAndUpdate({age:31},{$set:{name:"kiki"}},{upsert:true,returnNewDocument:true})
# $setOnInsert 标识指定了插入时的参数
# 下面语句表示找的到就展示,找不到就创建并展示
db.user.findOneAndUpdate({_id:"619c88322bd7557260e6886j"},{$setOnInsert:{name:"666g",_id:"619c88322bd7557260e68862"}},{upsert:true,returnNewDocument:true})