BSON is a binary serialization format used to store documents and make remote procedure calls in MongoDB. The BSON specification is located at bsonspec.org

BSON supports the following data types as values in documents. Each data type has a corresponding number and string alias that can be used with the $type operator to query documents by BSON type.

Type Number Alias Nodes
 Double  1  “double”  
 String  2  “string”  
 Object  3  “object”  
 Array  4  “array”  
 Binary data  5  “binData”  
 Undefined  6  “undefined”  Deprecated.
 ObjectId  7  “objectId”  
 Boolean  8  “bool”  
 Date  9  “date”  
 Null  10  “null”  
 Regular Expression  11  “regex”  
 DBPointer  12  “dbPointer”  Deprecated.
 JavaScript  13  “javascript”  
 Symbol  14  “symbol”  Deprecated.
 JavaScript (with scope)  15  “javascriptWithScope”  
 32-bit integer  16  “int”  
 Timestamp  17   “timestamp”  
 64-bit integer  18   “long”  
 Min key  -1   “minKey”  
 Max key  127  “maxKey”  

To determine a field’s type, see Check Types in the mongo Shell.

If you convert BSON to JSON, see the Extended JSON reference.

Comparison/Sort Order

When comparing values of different BSON types, MongoDB uses the following comparison order, from lowest to highest:

  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)

MongoDB treats some types as equivalent for comparison purposes. For instance, numeric types undergo conversion before comparison.

Changed in version 3.0.0: Date objects sort before Timestamp objects. Previously Date and Timestamp objects sorted together.

The comparison treats a non-existent field as it would an empty BSON Object. As such, a sort on the a field in documents { } and { a: null } would treat the documents as equivalent in sort order.

MongoDB sorts BinData in the following order:

  1. First, the length or size of the data.
  2. Then, by the BSON one-byte subtype.
  3. Finally, by the data, performing a byte-by-byte comparison.

The following sections describe special considerations for particular BSON types.

ObjectId

ObjectIds are small, likely unique, fast to generate, and ordered. ObjectId values consists of 12-bytes, where the first four bytes are a timestamp that reflect the ObjectId’s creation, specifically:

  • a 4-byte value representing the seconds since the Unix epoch,
  • a 3-byte machine identifier,
  • a 2-byte process id, and
  • a 3-byte counter, starting with a random value.

In MongoDB, each document stored in a collection requires a unique _id field that acts as a primary key. If an inserted document omits the _id field, the MongoDB driver automatically generates an ObjectId for the _id field.

This also applies to documents inserted through update operations with upsert: true.

MongoDB clients should add an _id field with a unique ObjectId. Using ObjectIds for the _id field provides the following additional benefits:

  • in the mongo shell, you can access the creation time of the ObjectId, using the ObjectId.getTimestamp() method.

  • sorting on an _id field that stores ObjectId values is roughly equivalent to sorting by creation time.

IMPORTANT: The relationship between the order of ObjectId values and generation time is not strict within a single second. If multiple systems, or multiple processes or threads on a single system generate values, within a single second; ObjectId values do not represent a strict insertion order. Clock skew between clients can also result in non-strict ordering even for values because client drivers generate ObjectId values.

SEE ALSO: ObjectId()

String

BSON strings are UTF-8. In general, drivers for each programming language convert from the language’s string format to UTF-8 when serializing and deserializing BSON. This makes it possible to store most international characters in BSON strings with ease. In addition, MongoDB $regex queries support UTF-8 in the regex string.

Timestamps

BSON has a special timestamp type for internal MongoDB use and is not associated with the regular Date type. Timestamp values are a 64 bit value where:

  • the first 32 bits are a time_t value (seconds since the Unix epoch)
  • the second 32 bits are an incrementing ordinal for operations within a given second.

Within a single mongod instance, timestamp values are always unique.

In replication, the oplog has a ts field. The values in this field reflect the operation time, which uses a BSON timestamp value.

NOTE: The BSON timestamp type is for internal MongoDB use. For most cases, in application development, you will want to use the BSON date type. See Date for more information.

If you insert a document containing an empty BSON timestamp in a top-level field, the MongoDB server will replace that empty timestamp with the current timestamp value. For example, if you create an insert a document with a timestamp value, as in the following operation:

var a = new Timestamp();
db.test.insert( { ts: a } );

Then, the db.test.find() operation will return a document that resembles the following:

{ "_id" : ObjectId("542c2b97bac0595474108b48"), "ts" : Timestamp(1412180887, 1) }

If ts were a field in an embedded document, the server would have left it as an empty timestamp value.

Changed in version 2.6: Previously, the server would only replace empty timestamp values in the first two fields, including _id, of an inserted document. Now MongoDB will replace any top-level field.

Date

BSON Date is a 64-bit integer that represents the number of milliseconds since the Unix epoch (Jan 1, 1970). This results in a representable date range of about 290 million years into the past and future.

The official BSON specification refers to the BSON Date type as the UTC datetime.

BSON Date type is signed. Negative values represent dates before 1970.

Example

Construct a Date using the new Date() constructor in the mongo shell:

var mydate1 = new Date()

Construct a Date using the ISODate() constructor in the mongo shell:

var mydate2 = ISODate()

Return the Date value as string:

mydate1.toString()

Return the month portion of the Date value; months are zero-indexed, so that January is month 0:

mydate1.getMonth()

MongoDB - Introduction to MongoDB, BSON Types的更多相关文章

  1. MongoDB - Introduction to MongoDB, MongoDB Extended JSON

    JSON can only represent a subset of the types supported by BSON. To preserve type information, Mongo ...

  2. MongoDB - Introduction to MongoDB, Documents

    MongoDB stores data records as BSON documents. BSON is a binary representation of JSON documents, th ...

  3. MongoDB - Introduction to MongoDB

    MongoDB is an open-source document database that provides high performance, high availability, and a ...

  4. MongoDB - Introduction to MongoDB, Databases and Collections

    MongoDB stores BSON documents, i.e. data records, in collections; the collections in databases. Data ...

  5. MongoDB - Introduction to MongoDB, Capped Collections

    Overview Capped collections are fixed-size collections that support high-throughput operations that ...

  6. mongoDB操作命令及mongoDB的helper

    此项目已开源,开源地址是: http://mongodbhelper-csharp.googlecode.com/svn/trunk/ mongodb的helper using System; usi ...

  7. mongoDB & Nodejs 访问mongoDB (一)

    最近的毕设需要用到mongoDB数据库,又把它拿出来再学一学,下盘并不是很稳,所以做一些笔记,不然又忘啦. 安装 mongoDB & mongoVUE mongoDB: https://www ...

  8. java操作mongodb & springboot整合mongodb

    简单的研究原生API操作MongoDB以及封装的工具类操作,最后也会研究整合spring之后作为dao层的完整的操作. 1.原生的API操作 pom.xml <!-- https://mvnre ...

  9. PHP使用MongoDB类操作MongoDB数据库总结

    参考:https://www.php.net/manual/zh/class.mongodb-driver-manager.php 参考:https://www.zhaokeli.com/articl ...

随机推荐

  1. Educational Codeforces Round 14 D. Swaps in Permutation (并查集orDFS)

    题目链接:http://codeforces.com/problemset/problem/691/D 给你n个数,各不相同,范围是1到n.然后是m行数a和b,表示下标为a的数和下标为b的数可以交换无 ...

  2. Codeforces Round #250 (Div. 1) D. The Child and Sequence (线段树)

    题目链接:http://codeforces.com/problemset/problem/438/D 给你n个数,m个操作,1操作是查询l到r之间的和,2操作是将l到r之间大于等于x的数xor于x, ...

  3. android WebView将新浪天气为我所用 ------>仅供娱乐

    新浪天气提供了一个网页     http://w.sina.com 浏览器访问: 这效果还可以了哦,直接用webview加载出来,效果也可以了哦,不过,这不是我要的.我不希望在我写的应用里到处铺满si ...

  4. Python3爬取中文网址

    本以为Python3的中文兼容性无比友好,结果还是会有一点问题的. 解决方案如下,就以爬取我自己的一个网页极简翻译为例 #coding:utf8 import urllib.request impor ...

  5. android 表情,软键盘冲突解决方案(仿微博等SNS应用)

    之前总想搞一下这个模块,可是由于忙碌总是推迟,现在就把这块好好的弥补过来,下面是我实现的思路.本人才疏学浅,还望大家不要见笑. 首先我们还是先看写示例:            上面应用应该不用我过多介 ...

  6. C# Func&lt;&gt;托付

    曾经我们为了可以调用一个方法.必须比照这种方法定义一个对应的delegate. 原先我们定义delegate // 托付声明 -- 定义一个签名: delegate double MathAction ...

  7. iOS开发——实用篇&提高iOS开发效率的方法和工具

    提高iOS开发效率的方法和工具 介绍 这篇文章主要是介绍一下我在iOS开发中使用到的一些可以提升开发效率的方法和工具. IDE 首先要说的肯定是IDE了,说到IDE,Xcode不能跑,当然你也可能同时 ...

  8. 【模式识别】Learning To Rank之RankBoost

    RankBoost的思想比較简单,是二元Learning to rank的常规思路:通过构造目标分类器,使得pair之间的对象存在相对大小关系.通俗点说,把对象组成一对对的pair,比方一组排序r1& ...

  9. C++中的inline函数

    内联函数: () 内联函数定义和作用: 将一个函数声明为inline,那么函数就成为内联函数.内联函数通常就是它在程序中每个调用点上“内联地”展开.从定义上看,内联函数跟一般函数不一样,一般函数调用的 ...

  10. Python学习 之 走进python

    1.Python:是一种解释型的.面向对象的.带有动态语义的高级程序设计语言. 2.Python发展阶段 —CNRI时期 —BeOpen时期 —DC时期 —Python 3.0 Python里程碑:2 ...