- Mastering MongoDB 3.x
- Alex Giamas
- 324字
- 2021-08-20 10:10:50
Comparing different data types
Due to the nature of MongoDB, it's perfectly acceptable to have different data type objects in the same field. This may happen by accident or on purpose (that is, null and actual values in a field)
The sorting order of different types of data is as follows from highest to lowest:
- MaxKey (internal type).
- Regular expression.
- Timestamp.
- Date.
- Boolean.
- ObjectId.
- BinData.
- Array.
- Object.
- Symbol, string.
- Numbers (ints, longs, doubles).
- Null.
- MinKey (internal type).
Non-existent fields get sorted as if they have null in the respective field. Comparing arrays is a bit more complex. An ascending order of comparison (or <) will compare the smallest element of each array. A descending order of comparison (or >) will compare the largest element of each array.
For example, see the following scenario:
> db.types.find()
{ "_id" : ObjectId("5908d58455454e2de6519c49"), "a" : [ 1, 2, 3 ] }
{ "_id" : ObjectId("5908d59d55454e2de6519c4a"), "a" : [ 2, 5 ] }
In ascending order, this is as follows:
> db.types.find().sort({a:1})
{ "_id" : ObjectId("5908d58455454e2de6519c49"), "a" : [ 1, 2, 3 ] }
{ "_id" : ObjectId("5908d59d55454e2de6519c4a"), "a" : [ 2, 5 ] }
Whereas in descending order it is as follows:
> db.types.find().sort({a:-1})
{ "_id" : ObjectId("5908d59d55454e2de6519c4a"), "a" : [ 2, 5 ] }
{ "_id" : ObjectId("5908d58455454e2de6519c49"), "a" : [ 1, 2, 3 ] }
The same applies when comparing an array with a single number value, as illustrated in the following example.
Inserting a new document with an integer value of 4:
> db.types.insert({"a":4})
WriteResult({ "nInserted" : 1 })
Descending sort:
> db.types.find().sort({a:-1})
{ "_id" : ObjectId("5908d59d55454e2de6519c4a"), "a" : [ 2, 5 ] }
{ "_id" : ObjectId("5908d73c55454e2de6519c4c"), "a" : 4 }
{ "_id" : ObjectId("5908d58455454e2de6519c49"), "a" : [ 1, 2, 3 ] }
Ascending sort:
> db.types.find().sort({a:1})
{ "_id" : ObjectId("5908d58455454e2de6519c49"), "a" : [ 1, 2, 3 ] }
{ "_id" : ObjectId("5908d59d55454e2de6519c4a"), "a" : [ b, 5 ] }
{ "_id" : ObjectId("5908d73c55454e2de6519c4c"), "a" : 4 }
In each case, we highlighted the values being compared in bold.
- 數據展現的藝術
- Ansible Quick Start Guide
- 計算機應用復習與練習
- Java開發技術全程指南
- 水晶石精粹:3ds max & ZBrush三維數字靜幀藝術
- 自動控制理論(非自動化專業)
- 水晶石影視動畫精粹:After Effects & Nuke 影視后期合成
- 大數據案例精析
- The DevOps 2.1 Toolkit:Docker Swarm
- 簡明學中文版Photoshop
- Creating ELearning Games with Unity
- Redash v5 Quick Start Guide
- Hands-On Business Intelligence with Qlik Sense
- 納米集成電路制造工藝(第2版)
- Getting Started with Tableau 2018.x