Mongodb教程未对字段{h}进行排序

时间:2018-09-17 22:45:56

标签: mongodb

我只是在玩简单的mongodb教程,当我尝试排序时似乎不起作用:

db.inventory.insertMany([
  { item: "journal", qty: 25, tags: ["blank", "red"], size: { h: 14, w: 21, uom: "cm" } },
  { item: "mat", qty: 85, tags: ["gray"], size: { h: 27.9, w: 35.5, uom: "cm" } },
  { item: "mousepad", qty: 25, tags: ["gel", "blue"], size: { h: 19, w: 22.85, uom: "cm" } }
])

然后

> db.inventory.find().sort({h:1})
{ "_id" : ObjectId("5ba02d6cc29157a810f9478b"), "item" : "journal", "qty" : 25, "tags" : [ "blank", "red" ], "size" : { "h" : 14, "w" : 21, "uom" : "cm" } }
{ "_id" : ObjectId("5ba02d6cc29157a810f9478c"), "item" : "mat", "qty" : 85, "tags" : [ "gray" ], "size" : { "h" : 27.9, "w" : 35.5, "uom" : "cm" } }
{ "_id" : ObjectId("5ba02d6cc29157a810f9478d"), "item" : "mousepad", "qty" : 25, "tags" : [ "gel", "blue" ], "size" : { "h" : 19, "w" :  22.85, "uom" : "cm" } }

因此,“ h”返回为14、27.9、19(未排序)。知道我在做什么错吗?

1 个答案:

答案 0 :(得分:1)

排序工作正常,只是您现在所期望的那样。这些文档不包含顶级字段h,因此所有文档均按null排序。

相反,您将需要使用dot notationsize.h进行排序。例如:

db.inventory.find().sort({ "size.h" : 1 } )
{ "_id" : ObjectId("5ba03209ebb1a32e62853cdf"), "item" : "journal", "qty" : 25, "tags" : [ "blank", "red" ], "size" : { "h" : 14, "w" : 21, "uom" : "cm" } }
{ "_id" : ObjectId("5ba03209ebb1a32e62853ce1"), "item" : "mousepad", "qty" : 25, "tags" : [ "gel", "blue" ], "size" : { "h" : 19, "w" : 22.85, "uom" : "cm" } }
{ "_id" : ObjectId("5ba03209ebb1a32e62853ce0"), "item" : "mat", "qty" : 85, "tags" : [ "gray" ], "size" : { "h" : 27.9, "w" : 35.5, "uom" : "cm" } }