我有這個文件:如何使用mongodb中的文檔和嵌入式文檔中的「_id」進行排序?
{
"_id" : ObjectId("5993e9ee92cf241648002a97"),
"name" : "test"
"subcategories" : [
{
"_id" : ObjectId("59953f20f4b8cf0595720e62"),
"name" : "subtest",
},
{
"_id" : ObjectId("59953f20f4b8cf0595720e63"),
"name" : "subtest2",
}
]
},
{
"_id" : ObjectId("5993e9ee92cf241648002a98"),
"name" : "test2"
"subcategories" : [
{
"_id" : ObjectId("59953f20f4b8cf0595720e66"),
"name" : "subtest3",
},
{
"_id" : ObjectId("59953f20f4b8cf0595720e69"),
"name" : "subtest4",
}
]
}
而且我想通過使用_id貓鼬進行排序兩種,文檔和嵌入的文檔。
事情是這樣的:
categoryModel.find({ }).sort({ _id: 1, "subcategories._id": 1 }).exec(function (err, data) {});
但我知道剛纔「_id:1」將工作。
這怎麼辦?
就做你是什麼意思?對返回的「文檔」進行排序?或者「將文檔中的數組元素**排序」返回?還有一些原因,爲什麼數組無法按照定義的順序「存儲」?並且請注意,默認情況下,任何數組都有「last last」,因爲這是您追加時發生的情況。 –
@NeilLunn我只是更新了我的問題 – WithoutBrain1994
您可以選擇所有的「類別」,並在服務器端對子類別進行排序:'... exec() 。然後(cats => {cats.each(cat => cat .subcategories.sort((a,b,)=> a._id.toString() - b._id.toString())); return cats; });'但是爲什麼你需要這樣做,當子類數組已經被'_id'命令了? – alexmac