学习mongo系列(五) AND,$or,$type

MongoDB OR 条件

MongoDB OR 条件语句使用了关键字 $or,语法格式如下:

>db.col.find(
   {
      $or: [
	     {key1: value1}, {key2:value2}
      ]
   }
).pretty()

 

> db.user.find({$or:[{"name":"admin","grade":"99"}]}).pretty()
> db.user.find({$or:[{"name":"admin","grade":"99"}]}).pretty()
> db.user.find({$or:[{"name":"admin"},{"grade":"99"}]}).pretty()
{
"_id" : ObjectId("56946fba3a18f4867aecbcd1"),
"name" : "admin",
"password" : "123456",
"title" : "admin",
"grade" : 50
}
> db.user.find({$or:[{{"grade":"99"},{"name":"admin"}]}).pretty()
...

没太明白$or的究竟

$type

 

MongoDB 中可以使用的类型如下表所示:

                    类型                 数字  备注   
Double 1  
String 2  
Object 3  
Array 4  
Binary data 5  
Undefined 6 已废弃。
Object id 7  
Boolean 8  
Date 9  
Null 10  
Regular Expression 11  
JavaScript 13  
Symbol 14  
JavaScript (with scope) 15  
32-bit integer 16  
Timestamp 17  
64-bit integer 18  
Min key 255 Query with -1.
Max key 127  

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

我们使用的数据库名称为"maxh" 我们的集合名称为"user",以下为我们插入的数据:

  

> db.user.find().pretty()
{
"_id" : ObjectId("56946fba3a18f4867aecbcd1"),
"name" : "admin",
"password" : "123456",
"title" : "admin",
"grade" : 50
}
{
"_id" : ObjectId("5694714a3a18f4867aecbcd2"),
"name" : "aaaaaaaaa",
"password" : "123456",
"grade" : 99
}
{
"_id" : ObjectId("5694ce6685cf2632ea951c05"),
"name" : "xiaoniao",
"password" : "lijian",
"grade" : "15"
}

 

查找grade的类型为string(type = 2)类型的记录(行)

> db.user.find({"grade":{$type:2}}).pretty()
{
"_id" : ObjectId("5694ce6685cf2632ea951c05"),
"name" : "xiaoniao",
"password" : "lijian",
"grade" : "15"
}

查找grade的类型为double(数值type = 1)行的记录

> db.user.find({"grade":{$type:1}}).pretty()
{
"_id" : ObjectId("56946fba3a18f4867aecbcd1"),
"name" : "admin",
"password" : "123456",
"title" : "admin",
"grade" : 50
}
{
"_id" : ObjectId("5694714a3a18f4867aecbcd2"),
"name" : "aaaaaaaaa",
"password" : "123456",
"grade" : 99
}

 

 

 

posted @ 2016-01-12 12:25  半天的半天  阅读(1515)  评论(0编辑  收藏  举报