我有這個示例資料
[
{id:1, type:"A", date:2022-01-01},
{id:2, type:"A", date:2022-01-02},
{id:3, type:"B", date:2022-01-01}
]
但是如何為每種型別只獲取一個資料,就像我必須得到這樣的輸出。
[
{id:2, type:"A", date:2022-01-02},
{id:3, type:"B", date:2022-01-01}
]
如果具有相同的型別值,則只獲取一個資料。我試過 $group $first 但沒有作業。任何人都可以幫助我嗎?我應該在 mongodb 中編碼什么?
uj5u.com熱心網友回復:
不確定什么對您不起作用,但是$groupand $first(or $last) 是要走的路,如下所示:
db.collection.aggregate([
{
$group: {
_id: "$type",
root: {
$first: "$$ROOT"
}
}
},
{
$replaceRoot: {
newRoot: "$root"
}
}
])
蒙戈游樂場
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/444035.html
