給定第一個代碼塊是示例資料,第二個塊是我想要的輸出在 MongoDB 中添加Machine Stats欄位所需的查詢是什么所以我想要的輸出是這個(基本上添加machine stats陣列中的所有欄位)
{
"date" : ISODate("2022-04-01T00:00:00.000Z"),
"intervalName" : "Shift A",
"operatorId" : "85875678",
"__v" : 0,
"clientId" : "ywegduywy",
"createdAt" : ISODate("2022-05-05T07:33:08.183Z"),
"deleted" : false,
"machineStats" : [
{
"idleTime" : 10,
"breaks" : 10,
"loading" : 10,
"unloading" : 10,
"runtime" : 11,
"total" : 100,
"activity" : {}
},
{
"idleTime" : 10,
"breaks" : 10,
"loading" : 10,
"unloading" : 10,
"runtime" : 10,
"total" : 100,
"activity" : {}
}
],
"plantId" : "AACCS3034M-SEZ-01",
"totalActivity" : 10,
"totalAll" : 100,
"totalBreaks" : 10,
"totalIdleTime" : 10,
"totalLoadUnload" : 10,
"totalRuntime" : 10,
"updatedAt" : ISODate("2022-05-05T07:33:30.213Z")
}
我想要的期望輸出(基本上除了活動之外的機器統計陣列中的所有欄位)
{
"date" : ISODate("2022-04-01T00:00:00.000Z"),
"intervalName" : "Shift A",
"operatorId" : "495632582487",
"__v" : 0,
"clientId" : "AACCS3034M",
"createdAt" : ISODate("2022-05-05T07:33:08.183Z"),
"deleted" : false,
"machineStats" : [
{
"idleTime" : 20,
"breaks" : 20,
"loading" : 20,
"unloading" :20,
"runtime" : 21,
"total" : 200,
"activity" : {}
},
],
"plantId" : "AACCS3034M-SEZ-01",
"totalActivity" : 10,
"totalAll" : 100,
"totalBreaks" : 10,
"totalIdleTime" : 10,
"totalLoadUnload" : 10,
"totalRuntime" : 10,
"updatedAt" : ISODate("2022-05-05T07:33:30.213Z")
}
uj5u.com熱心網友回復:
一種方法是使用$reduce迭代陣列并將每個專案的資料添加到累積資料中,如下所示:
db.collection.aggregate([
{
$set: {
machineStats: {
$reduce: {
input: "$machineStats",
initialValue: {
idleTime: 0,
breaks: 0,
loading: 0,
unloading: 0,
runtime: 0,
total: 0
},
in: {
idleTime: {$add: ["$$value.idleTime", "$$this.idleTime"]},
breaks: {$add: ["$$value.breaks", "$$this.breaks"]},
loading: {$add: ["$$value.loading", "$$this.loading"]},
unloading: {$add: ["$$value.unloading", "$$this.unloading"]},
total: {$add: ["$$value.total", "$$this.total"]},
runtime: {$add: ["$$value.runtime", "$$this.runtime"]}
}
}
}
}
}
])
游樂場示例。
另一種選擇是使用$unwind,$group但對于此特定請求的輸出,它的效率應該較低。
uj5u.com熱心網友回復:
您可以使用map和reduce方法在 mongo 查詢中完成這種計算。
- 減少:https ://www.mongodb.com/docs/manual/reference/operator/aggregation/reduce/
- 地圖:https ://www.mongodb.com/docs/manual/reference/operator/aggregation/map/
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/476444.html
上一篇:將資料框的值更改為列名并為其賦值
