我有一個類似的集合:
{"name": 'C', "dateTime": "Oct 19 14:52"}
{"name": 'B', "dateTime": "Oct 19 14:52"}
{"name": 'A', "dateTime": "Oct 19 16:52"}
{"name": 'C', "dateTime": "Oct 19 15:52"}
{"name": 'B', "dateTime": "Oct 19 16:52"}
在我使用排序之后
$sort: {
"dateTime": 1,
"name": 1
}
我得到了這個結果:
{"name": 'B', "dateTime": "Oct 19 14:52"}
{"name": 'C', "dateTime": "Oct 19 14:52"}
{"name": 'C', "dateTime": "Oct 19 15:52"}
{"name": 'A', "dateTime": "Oct 19 16:52"}
{"name": 'B', "dateTime": "Oct 19 16:52"}
但是,我想要的結果是按時間排序后,我想像這樣對它們進行分組:
{"name": 'B', "dateTime": "Oct 19 14:52"}
{"name": 'B', "dateTime": "Oct 19 16:52"}
{"name": 'C', "dateTime": "Oct 19 14:52"}
{"name": 'C', "dateTime": "Oct 19 15:52"}
{"name": 'A', "dateTime": "Oct 19 16:52"}
請問怎樣才能達到上面的結果,謝謝
uj5u.com熱心網友回復:
您首先需要$group根據名稱首先查看您的檔案。使用陣列來保存檔案,$sort它們根據您的排序。$unwind他們取回原始檔案。
db.collection.aggregate([
{
$group: {
_id: "$name",
docs: {
$push: "$$ROOT"
}
}
},
{
$sort: {
"docs.dateTime": 1,
"docs.name": 1
}
},
{
"$unwind": "$docs"
},
{
"$replaceRoot": {
"newRoot": "$docs"
}
}
])
這是Mongo 游樂場供您參考。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/344953.html
上一篇:kafka生產者實作細節
下一篇:查找mongodb后查詢陣列
