我想知道mongodb聚合中的$addFields
或$project
中间阶段之间是否存在性能差异
让我们假设这些数据:
{"_id":"5c9b88648a2b5700118e5a05","values":[5,8,2],"piv":1}
{"_id":"5c9b88658a2b5700118e5a06","values":[9,8,2],"piv":1}
{"_id":"5c9b88658a2b5700118e5a07","values":[1,8,2],"piv":2}
{"_id":"5c9b88658a2b5700118e5a08","values":[5,3,2],"piv":2}
这两个聚合之间是否存在性能差异(这只是一个示例):
db.test.aggregate([{
// This is the stage that will change
$addFields: {
v: {
$reduce: {
input: '$values',
initialValue: 0,
in: {
$sum: ["$$value", "$$this"]
}
}
}
}
}, {
$group: {
_id: '$piv',
vals: {
$sum: '$v'
}
}
}])
和
db.test.aggregate([{
// This is the stage that will change
$project: {
piv: 1,
v: {
$reduce: {
input: '$values',
initialValue: 0,
in: {
$sum: ["$$value", "$$this"]
}
}
}
}
}, {
$group: {
_id: '$piv',
vals: {
$sum: '$v'
}
}
}])