如何获得 objects 不同的两个值的平均值?
How to get average of two values which are in different objects?
我的数据如下:
[
{
"_id": ObjectId("6213baa5a013b7c5f1232e23"),
"birthDate": ISODate("1973-05-01T13:30:15Z"),
"surname": "Johnson",
"name": "Emma",
"registerDate": ISODate("1900-06-11T17:30:15Z"),
"children": [
{
"birthDate": ISODate("1993-05-21T16:30:15Z"),
"surname": "Johnson",
"name": "Liam"
},
{
"birthDate": ISODate("1994-01-21T15:30:15Z"),
"surname": "Johnson",
"name": "Olivia",
"registerDate": ISODate("2019-09-14T12:30:15Z")
}
],
"city": "Houston"
}
]
我想计算具有 registerDate 的人的注册年龄。在这个例子中,我应该得到 Emma(parent) 和 Olivia(child) 的平均注册年龄。我试过了this。
我计算了注册年龄并将它们添加为一个字段。我得到了奥利维亚的注册年龄。但是,我有艾玛的重复注册年龄。我想使用其中之一。我怎样才能得到属于艾玛和奥利维亚的平均注册年龄。我的意思是 (5+1)/2=3
。您可以在添加的 link 中看到这些值。
你可以先用$map
得到ages数组。然后使用 $avg
得到平均年龄。
$avg
ignores non-numeric values, including missing values. If all of the operands for the average are non-numeric, $avg
returns null
since the average of zero values is undefined
.
[
{
"$addFields": {
"ages": {
"$map": {
"input": "$children",
"as": "child",
"in": {
$dateDiff: {
startDate: "$$child.registerDate",
endDate: "$$NOW",
unit: "year"
}
}
}
}
}
},
{
"$addFields": {
averageAge: {
"$avg": {
"$concatArrays": [
"$ages",
[
{
$dateDiff: {
startDate: "$registerDate",
endDate: "$$NOW",
unit: "year"
}
}
]
]
}
}
}
}
]
我的数据如下:
[
{
"_id": ObjectId("6213baa5a013b7c5f1232e23"),
"birthDate": ISODate("1973-05-01T13:30:15Z"),
"surname": "Johnson",
"name": "Emma",
"registerDate": ISODate("1900-06-11T17:30:15Z"),
"children": [
{
"birthDate": ISODate("1993-05-21T16:30:15Z"),
"surname": "Johnson",
"name": "Liam"
},
{
"birthDate": ISODate("1994-01-21T15:30:15Z"),
"surname": "Johnson",
"name": "Olivia",
"registerDate": ISODate("2019-09-14T12:30:15Z")
}
],
"city": "Houston"
}
]
我想计算具有 registerDate 的人的注册年龄。在这个例子中,我应该得到 Emma(parent) 和 Olivia(child) 的平均注册年龄。我试过了this。
我计算了注册年龄并将它们添加为一个字段。我得到了奥利维亚的注册年龄。但是,我有艾玛的重复注册年龄。我想使用其中之一。我怎样才能得到属于艾玛和奥利维亚的平均注册年龄。我的意思是 (5+1)/2=3
。您可以在添加的 link 中看到这些值。
你可以先用$map
得到ages数组。然后使用 $avg
得到平均年龄。
$avg
ignores non-numeric values, including missing values. If all of the operands for the average are non-numeric,$avg
returnsnull
since the average of zero values isundefined
.
[
{
"$addFields": {
"ages": {
"$map": {
"input": "$children",
"as": "child",
"in": {
$dateDiff: {
startDate: "$$child.registerDate",
endDate: "$$NOW",
unit: "year"
}
}
}
}
}
},
{
"$addFields": {
averageAge: {
"$avg": {
"$concatArrays": [
"$ages",
[
{
$dateDiff: {
startDate: "$registerDate",
endDate: "$$NOW",
unit: "year"
}
}
]
]
}
}
}
}
]