gpt4 book ai didi

arrays - 数组数组的简单计算

转载 作者:行者123 更新时间:2023-12-02 21:38:08 27 4
gpt4 key购买 nike

我有以下收藏:

{
"price" : [
55800000,
62800000
],
"surface" : [
81.05,
97.4
],
}

我想计算每平方米的价格。我已尝试以下操作,但出现以下错误:“$divide 仅支持数字类型,不支持数组和数组”

db.entries.aggregate(
[
{ $project: { url: 1, pricePerSquareMeter: { $divide: [ "$price", "$surfaces" ] } } }
]
)

你知道如何解决这个问题吗?最终想要有一个像这样的数组:

{
"price" : [
55800000,
62800000
],
"surface" : [
81.05,
97.4
],
"pricePerSquareMeter" : [
688463.91,
644763.86
]
}

重要:价格和面积也应排序,以便计算有效。

最佳答案

您可以使用以下聚合

db.collection.aggregate([
{ "$addFields": {
"pricePerSquareMeter": {
"$map": {
"input": { "$range": [0, { "$size": "$price" }] },
"in": {
"$divide": [
{ "$arrayElemAt": ["$price", "$$this"] },
{ "$arrayElemAt": ["$surface", "$$this"] }
]
}
}
}
}}
])

MongoPlayground

关于arrays - 数组数组的简单计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57834264/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com