CRUD练习笔记:
Create(增加):
增加一个users表的集合:
db.createCollection("users")
往users添加BJON数据
db.users.insert({name:"sue",age:36,status:"A",groups:["news","sports"]})
db.users.insert({name:"jim",age:18,status:"B",groups:["news","sports"]})
db.users.insert({name:"lily",age:32,status:"C",groups:["news","sports"]})
翻译成sql:
insert into user (name,age,status) values ("sue","26","A")
Read(查询/读):
查看集合的内容
db.users.find()
在MongoDB中查看内容可以指定条件
db.user.find({age:{$gt:18}},{name:1,age:1}).limit(5)
翻译成sql:
select _id,name,age
from users
where age>18
limit 5
还可以写成这样(按age来进行升序排序,如果是1的话就升序,如果是-1的话就降序,limit(5)限制只能查出5条数据):
db.users.find({age:{$gt:18}},{name:1,age:1}).limit(5).sort({age:1})
如果查询的时候想排除某个字段,将1改成0,可以这样写:
db.users.find({age:{$gt:18}},{_id:0,name:1,age:1}).limit(5).sort({age:1})
Update(更新):
1)db.user.update({age:32},{$set:{status:"c"}})
2)db.user.update({age:{$gt:32}},{$set:{status:"c"}})
翻译成sql:
1) update user
set status=‘A‘
where age=32
2) update user
set status=‘A‘
where age>32
需要注意的是:这样也只是更新一条数据,必须添加{multi:true}才能实现多行更新
应该写成:
db.user.update({age:{$gt:32}},{$set:{status:"c"}},{multi:true})
Delete(删除):
db.user.remove( {status:"D"})
翻译成sql:
delete from user
where status=‘D‘