Mongo游樂場鏈接:https ://mongoplayground.net/p/BGtxQEBAvZh
我有一個陣列欄位“opcoes”,我想按 date 排序dt。目前它是未排序的,例如
{
"_id" : "w900c9b5a-666f-4857-92da-0b9c273dca40",
"opcoes" : [
{
"dt" : ISODate("2021-11-16T11:17:55.386-03:00"),
"text" : "2"
},
{
"dt" : ISODate("2021-11-16T11:17:29.709-03:00"),
"text" : "3"
}
]
}
預期結果是:
{
"_id" : "w900c9b5a-666f-4857-92da-0b9c273dca40",
"opcoes" : [
{
"dt" : ISODate("2021-11-16T11:17:29.709-03:00") ,
"text" : "3"
},
{
"dt" : , ISODate("2021-11-16T11:17:55.386-03:00")
"text" : "2"
}
]
}
你能幫助我嗎?我試圖使用$SortArray但它無法識別它。我得到“ Invalid $project :: 由 :: Unknown expression $sortArray 引起”。
我使用以下方法創建了陣列$push:
{
$group: {
_id: "$chat_key",
opcoes: {
$push: {
text: "$text",
dt: "$dt"
}
}
}
}
有沒有在 a 內排序的選項$push?
謝謝
uj5u.com熱心網友回復:
$sortArray適用于 mongoDB 5.2及更高版本,如果您收到此錯誤,您可能使用的是舊版本。
無論您的版本如何,最好的方法是$sort在$push:
db.collection.aggregate([
{
$sort: {dt: 1}
},
{
$group: {
_id: "$chat_key",
opcoes: {$push: {text: "$text", dt: "$dt"}}
}
])
如果您已經有一個陣列(并且您無法控制推送操作),并且您的版本早于 5.2,您可以$unwind:
db.collection.aggregate([
{
$unwind: "$opcoes"
},
{
$sort: {dt: 1}
},
{
$group: {
_id: "$_id",
opcoes: {
$push: {dt: "$opcoes.dt", text: "$opcoes.text"}
}
}
}
])
操場
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/481380.html
上一篇:旋轉檔案名中已有日期時間的檔案
