查询某个字段是否存在
db.student.findOne({name:{$exists:true}})
db.student.findOne({'department.name':{$exists:true}})
db.student.findOne({'department.name':{$exists:false}})
-------------------------------------------------------------------------------
判断map对象是否为空,注意不能通过$gt,$lt来判断size大小,可以利用索引来判断
db.student.find({class: {$not: {$size: 0}}}).limit(2)
db.student..find({'class.0': {$exists: 1}})
----------------------------------------------------------------------------------
判断一个数组的size
db.student..find({'class': {$size: 3}})
db.student.find({ $where: "this.class.length < 3" })
---------------------------------------------------------------------------------
格式化输出
select top 1 *from student;
db.student.findOne()
select top 1 *from student where age>15;
db.student.findOne({age:{$gt:15}})
select class,department from student where name='shell' and gender=true;
db.student.findOne({name:shell,gender:true},{class:1,department:1})
---------------------------------------------------------------------------------
游标跳转查询和限定返回的个数
db.department.find().skip(10)
select top 10 *from department;
db.department.find().limit(10)
---------------------------------------------------------------------------------
值返回指定字段,第一个map写filter条件,第二个map写返回的字段,默认会返回_id,如果不需要可以设置_id:0
db.student.find({},{name:1,id:1}
db.student.find({},{name:1,id:1,_id:0}
--------------------------------------------------------------------------------------
查询总数
db.student.find().count()
db.student.find({age:{$lt:20}}).count()
-----------------------------------------------------------------------------------
更新和删除某个字段:删除第一个class和修改更新时间为当前时间
更新或添加字段使用$set
删除字段使用unset
db.student.update({id:10005},{$unset:{'class.0':1},$set:{updated:NumberLong(new Date().valueOf()/1000)}})
------------------------------------------------------------------------------------
kill锁
先用这个命令查看锁,找到你要kill的pid
db.currentOp()
将上一步查找到的pid写入括号内,执行以下命令就干掉了
db.killOp(pid)
-------------------------------------------------------------------------------------
重命名字段
db.test.update({}, {$rename : {"a" : "b"}}, false, true)
-------------------------------------------------------------------------------------
在数组中插入元素
db.users.update({"name":"zhang"},{"$addToSet":{"age":18}})
-------------------------------------------------------------------------------------
删除整条记录
delete from test where key='test1';
db.test.remove({'key':'test1'})