官术网_书友最值得收藏!

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:

  1. MaxKey (internal type).
  2. Regular expression.
  3. Timestamp.
  4. Date.
  5. Boolean.
  6. ObjectId.
  7. BinData.
  8. Array.
  9. Object.
  10. Symbol, string.
  11. Numbers (ints, longs, doubles).
  12. Null.
  13. 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.

主站蜘蛛池模板: 凤山市| 万山特区| 泾源县| 龙川县| 福鼎市| 太原市| 合阳县| 浮梁县| 隆尧县| 库车县| 大新县| 沁水县| 湖北省| 皮山县| 灌云县| 威信县| 股票| 澎湖县| 上虞市| 宜君县| 慈溪市| 南昌县| 上思县| 枣强县| 宁波市| 余江县| 上杭县| 微山县| 吉安市| 昭平县| 清镇市| 兴义市| 双鸭山市| 进贤县| 乌海市| 多伦县| 新平| 麻栗坡县| 惠来县| 鄱阳县| 依兰县|