JSON是一种被广泛使用的轻量级的数据交换格式,支持现今绝大多数主流的开发语言。而近几年崛起的mongDB则采用了类JSON的数据格式,在JSON之上进行了丰富和增强,使得mongoDB可以处理及报错更大的数据类型。本文就2者进行描述同时给出mongoDB支持的数据类型。 一、JSON特性 1、什么事JSON 2、JSON 数据的书写格式 3、JSON仅支持以下数据类型 4、JSON基于两种结构: 1、什么是BSON 2、BSON的特定 3、mongoDB与BSON //null值 db.mycol.insert({x:null}) WriteResult({ “nInserted” : 1 }) //布尔型 db.mycol.insert({x:true}) WriteResult({ “nInserted” : 1 }) //小数 db.mycol.insert({x:3.1515}) WriteResult({ “nInserted” : 1 }) //整数 db.mycol.insert({x:3}) WriteResult({ “nInserted” : 1 }) //4字节带符合整数 db.mycol.insert({x:NumberInt(“3”)}) WriteResult({ “nInserted” : 1 }) //8字节带符号整数 db.mycol.insert({x:NumberLong(“3”)}) WriteResult({ “nInserted” : 1 }) //字符型 db.mycol.insert({x:”robin”}) WriteResult({ “nInserted” : 1 }) //日期型 db.mycol.insert({x:new Date()}) WriteResult({ “nInserted” : 1 }) //正则表达式 db.mycol.insert({x:/u01/i}) WriteResult({ “nInserted” : 1 }) //数组 db.mycol.insert({x:[“a”,”b”,”c”]}) WriteResult({ “nInserted” : 1 }) //嵌套文档 db.mycol.insert({x:{y:”nested”}}) WriteResult({ “nInserted” : 1 }) //对象id db.mycol.insert({x:ObjectId()}) WriteResult({ “nInserted” : 1 }) //代码段 db.mycol.insert({x:function(){/ This is a test code /}}) WriteResult({ “nInserted” : 1 }) //查找集合mycol的文档 db.mycol.find({},{_id:0}) { “x” : null } { “x” : true } { “x” : 3.1515 } { “x” : 3 } //Author : Leshami { “x” : 3 } //Blog : http://blog.csdn.net/leshami { “x” : NumberLong(3) } { “x” : “robin” } { “x” : ISODate(“2016-09-06T02:46:35.173Z”) } { “x” : /u01/i } { “x” : [ “a”, “b”, “c” ] } { “x” : { “y” : “nested” } } { “x” : ObjectId(“57ce2f34ce8685a6fd9df3ae”) } { “x” : function (){/ This is a test code /} } //undefined类型 db.mycol.insert({name:undefined}); WriteResult({ “nInserted” : 1 }) db.mycol.insert({name:”123”}); WriteResult({ “nInserted” : 1 }) printjson(db.mycol.find().toArray()) [ { “_id” : ObjectId(“57ce1cc8c60f1fe489e49c68”), “name” : undefined }, { “_id” : ObjectId(“57ce1cdbc60f1fe489e49c69”), “name” : “123” } ] //查找undefined类型的文档 db.mycol.find({name:”undefined”}) db.mycol.find({name:undefined}) Error: error: { “waitedMS” : NumberLong(0), “ok” : 0, “errmsg” : “cannot compare to undefined”, “code” : 2 } db.mycol.find({name:{$type:6}}) { “_id” : ObjectId(“57ce1cc8c60f1fe489e49c68”), “name” : undefined } db.mycol.find({name:{$type:”undefined”}}) { “_id” : ObjectId(“57ce1cc8c60f1fe489e49c68”), “name” : undefined } //mongoDB数据类型的比较与排序优先级 1) MinKey (internal type) 2) Null 3) Numbers (ints, longs, doubles) 4) Symbol, String 5) Object 6) Array 7) BinData 8) ObjectId 9) Boolean 10) Date 11) Timestamp 12) Regular Expression 13) MaxKey (internal type) 5、关于_id与Object_Id a 4-byte value representing the seconds since the Unix epoch, //时间戳 { “_id” : ObjectId(“57ce2d4cce8685a6fd9df3a3”), “x” : null } 57ce2d4c //时间戳 ==>1473129804 ==> 2016/9/6 10:43:24 ce8685 //机器唯一标识码 a6fd //进程ID 9df3a3 //随机数 |