1. 准备工作
(1)启动mongo
进入mongo安装目录的bin/ 目录 , ./mongod
(2)启动mongo客户端
./mongo
(3) 查看所有库
show dbs;
(4) 切换到lvyf库
use lvyf
(5) 查看所有的集合
show collections;
(6)从一个集合中查数据
db.first_col.find();
2. 查询
(1) 查看所有 , pretty() 作用就是格式化json数据
db.collection_name.find().pretty();
> db.first_col.find()
{ "_id" : ObjectId("575e879380d09b176a58ce64"), "name" : "lvyafei", "age" : 21, "sex" : "M", "address" : "http://www.lvyf.com" }
{ "_id" : ObjectId("575e880980d09b176a58ce65"), "name" : "chenjl", "age" : 20, "sex" : "W", "address" : "http://www.chenjl.com" }
{ "_id" : ObjectId("575e889880d09b176a58ce66"), "name" : "child", "age" : 2, "sex" : "M", "address" : "http://www.child.com", "status" : "cry and laugh" }
(2) 条件查询
操作
|
格式 |
例子 |
对应的sql语句 |
等于
|
{ key : value } |
{name : lvyf } |
where name=‘lvyf‘ |
小于
|
{key : {< : value } } |
{age : {< : 20 } } |
where age <20 |
小于或等于
|
{key : {<e : value }} |
{age : {<e : 20 }} |
where age <=20 |
大于
|
{key : { > : value }} |
{age : {> : 3}} |
where age > 3 |
大于或等于
|
{key : {>e : vlaue }} |
{age : {>e : 3 }} |
where age >=3 |
不等于 |
{key : {&ne : value }} |
{name : {&ne : lvyf }} |
where name !=‘lvyf‘
|
(3)and 条件
根据性别和名字查询记录 , 对应sql语句where name= ‘lvyafei‘ and sex = ‘M‘
> db.first_col.find({name : "lvyafei" , sex : "M"}).pretty()
{
"_id" : ObjectId("575e879380d09b176a58ce64"),
"name" : "lvyafei",
"age" : 21,
"sex" : "M",
"address" : "http://www.lvyf.com"
}
(4) or 条件,语法
db.collection_name.find( { $or :[
{key1 : value1} , {key2 : value2 }
] } );
根据名字或者性别查询例子:
> db.first_col.find({$or : [ {name:"lvyafei" },{sex : ‘M‘}] })
{ "_id" : ObjectId("575e879380d09b176a58ce64"), "name" : "lvyafei", "age" : 21, "sex" : "M", "address" : "http://www.lvyf.com" }
{ "_id" : ObjectId("575e889880d09b176a58ce66"), "name" : "child", "age" : 2, "sex" : "M", "address" : "http://www.child.com", "status" : "cry and laugh" }
(5) and 和 or 联合使用,相当于 where age >= 3 and ( name=‘lvyafei‘ or sex=‘M‘ )
> db.first_col.find({age : {$gte : 3}, $or:[{name:"lvyafei"} , {set : ‘M‘}]}).pretty()
{
"_id" : ObjectId("575e879380d09b176a58ce64"),
"name" : "lvyafei",
"age" : 21,
"sex" : "M",
"address" : "http://www.lvyf.com"
}
(6) 大于和小于联合查询,相当于 where age > 3 and age <21
> db.first_col.find({"age" : {$lt : 21,$gt:3}})
{ "_id" : ObjectId("575e880980d09b176a58ce65"), "name" : "chenjl", "age" : 20, "sex" : "W", "address" : "http://www.chenjl.com" }
(7) $type操作符
如果要查询 name 是string 类型的记录
> db.first_col.find({name : {$type : 2}});
{ "_id" : ObjectId("575e879380d09b176a58ce64"), "name" : "lvyafei", "age" : 21, "sex" : "M", "address" : "http://www.lvyf.com" }
{ "_id" : ObjectId("575e880980d09b176a58ce65"), "name" : "chenjl", "age" : 20, "sex" : "W", "address" : "http://www.chenjl.com" }
{ "_id" : ObjectId("575e889880d09b176a58ce66"), "name" : "child", "age" : 2, "sex" : "M", "address" : "http://www.child.com", "status" : "cry and laugh" }
mongDB-- 3. 查询操作