db.collection('selected_properties').aggregate([
{
$match : { presentation_id : ObjectId(req.body.presentation_id),
checked_status : true}
},
{
$lookup : { from :'properties', localField : 'property_id',
foreignField : '_id', as : 'property_info'}
},
{
$unwind : {path : '$property_info', preserveNullAndEmptyArrays : true}
},
{
$sort : {'property_info.ListPrice' : 1}
},
{
$group:
{
_id: "$user_id",
minActiveListPrice: { $min: { $cond: [ {
$eq: [ "$property_info.StandardStatus", "A" ]},
'$property_info.ListPrice','' ] } },
maxActiveListPrice: { $max: { $cond: [ {
$eq: [ "$property_info.StandardStatus", "A" ]},
'$property_info.ListPrice',0 ] } },
avgActiveListPrice: { $avg: { $cond: [ {
$eq: [ "$property_info.StandardStatus", "A" ]},
'$property_info.ListPrice','' ] } },
medianActiveListprice: { $push: { $cond: [ {
$eq: [ "$property_info.StandardStatus", "A" ]},
'$property_info.ListPrice',null ] } },
avgPrice: { $avg: "$property_info.ListPrice" },
maxPrice: { $max: "$property_info.ListPrice" },
minPrice: { $min: "$property_info.ListPrice" },
median: { $push: "$property_info.ListPrice"}
}
},
{ "$project": {
"minActiveListPrice":1,
"maxActiveListPrice":1,
"avgActiveListPrice":1,
"avgPrice": 1,
"maxPrice": 1,
"minPrice": 1,
"medianActiveListpricevalue": {
$let: {
vars: {
arr: { $filter: {
input: "$medianActiveListprice",
as: "aa",
cond: {$ne:["$$aa",null]}
}},
},
in: { "$cond": {
"if": {
"$eq": [{$mod: [ {$size:"$$arr"}, 2 ]}, 0]
},
"then": {
$avg:[
{ $arrayElemAt: [ "$$arr", {$subtract:[{$divide: [ {$size:"$$arr"}, 2 ]},1]}]},
{ $arrayElemAt: [ "$$arr", {$divide: [ {$size:"$$arr"}, 2 ]}]}
]
},
"else": {
$arrayElemAt: [ "$$arr",{$floor : {$divide: [ {$size:"$$arr"}, 2 ]}}]
}
}}
}
},
"medianvalue":{ "$cond": {
"if": {
"$eq": [{$mod: [ {$size:"$median"}, 2 ]}, 0]
}
"then": {
$avg:[
{ $arrayElemAt: [ "$median", {$subtract:[{$divide: [ {$size:"$median"}, 2 ]},1]}]},
{ $arrayElemAt: [ "$median", {$divide: [ {$size:"$median"}, 2 ]}]}
]
},
"else": {
$arrayElemAt: [ "$median",{$floor : {$divide: [ {$size:"$median"}, 2 ]}}]
}
}}
} }
])