我有一個收藏。
{
"_id" : "410a7cb2-7ee1-4e7a-9fb7-fa651fcaa4e5",
"reqHistoryEvents" : [
{
"reqHistoryMsg" : "abcd",
"reqHistoryCreatedAt" : ISODate("2022-04-27T08:18:30.850 0000"),
},
{
"reqHistoryMsg" : "EFGH ",
"reqHistoryCreatedAt" : ISODate("2022-04-27T08:22:12.716 0000"),
},
{
"reqHistoryMsg" : "IJKL",
"reqHistoryCreatedAt" : ISODate("2022-04-27T08:22:12.716 0000"),
}
]
}
我想把它轉換成這個 :::::
{
"_id" : "410a7cb2-7ee1-4e7a-9fb7-fa651fcaa4e5",
"reqHistoryEvents" : [
{
"reqHistoryMsg" : "abcd",
"reqHistoryCreatedAt" : ISODate("2022-04-27T08:18:30.850 0000"),
},
{
"reqHistoryMsg" : ["EFGH ","IJKL"],
"reqHistoryCreatedAt" : ISODate("2022-04-27T08:22:12.716 0000"),
}
]
}
基本上它將基于創建時間戳。如果我們有相同的 reqHistoryCreatedAt,我們需要合并 reqHistoryMsg。
我無法撰寫mongo查詢。有什么幫助嗎?
uj5u.com熱心網友回復:
$unwind- 解構reqHistoryEvents陣列欄位。$group_id- 按和reqHistoryEvents.reqHistoryCreatedAt欄位分組。添加reqHistoryMsg到陣列中。$group_id- 按欄位分組并形成reqHistoryEvents陣列。
db.collection.aggregate([
{
$unwind: "$reqHistoryEvents"
},
{
$group: {
_id: {
_id: "$_id",
reqHistoryCreatedAt: "$reqHistoryEvents.reqHistoryCreatedAt"
},
reqHistoryMsg: {
$push: "$reqHistoryEvents.reqHistoryMsg"
}
}
},
{
$group: {
_id: "$_id._id",
reqHistoryEvents: {
$push: {
reqHistoryMsg: "$reqHistoryMsg",
reqHistoryCreatedAt: "$_id.reqHistoryCreatedAt"
}
}
}
}
])
示例 Mongo Playground
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/466273.html
