Reputation: 77
I have a collection :
{
_id : xxx,
children : [
{
childrenOfChildren : [
{
price : xxx
},
{
price : xxx
},
{
price : xxx
}
]
},
{
childrenOfChildren : [
{
price : xxx
},
{
price : xxx
},
{
price : xxx
}
]
},
{
childrenOfChildren : [
{
price : xxx
},
{
price : xxx
},
{
price : xxx
}
]
}
]
},
{
_id : xxx,
children : [
{
childrenOfChildren : [
{
price : xxx
},
{
price : xxx
},
{
price : xxx
}
]
},
{
childrenOfChildren : [
{
price : xxx
},
{
price : xxx
},
{
price : xxx
}
]
},
{
childrenOfChildren : [
{
price : xxx
},
{
price : xxx
},
{
price : xxx
}
]
}
]
},
{
_id : xxx,
children : [
{
childrenOfChildren : [
{
price : xxx
},
{
price : xxx
},
{
price : xxx
}
]
},
{
childrenOfChildren : [
{
price : xxx
},
{
price : xxx
},
{
price : xxx
}
]
},
{
childrenOfChildren : [
{
price : xxx
},
{
price : xxx
},
{
price : xxx
}
]
}
]
},
{
_id : xxx,
children : [
{
childrenOfChildren : [
{
price : xxx
},
{
price : xxx
},
{
price : xxx
}
]
},
{
childrenOfChildren : [
{
price : xxx
},
{
price : xxx
},
{
price : xxx
}
]
},
{
childrenOfChildren : [
{
price : xxx
},
{
price : xxx
},
{
price : xxx
}
]
}
]
}
Every entry has an array named children. And Every entry in children has an array named childrenOfChildren. And every entry in childrenOfChildren has an attribute named price. I wanna get maximum value of price in this overall collection. How can I achieve this? Please help me!
Upvotes: 3
Views: 2003
Reputation: 9295
you can do this using $unwind and $group.
db.collection.aggregate([
{
$unwind:"$children"
},
{
$unwind:"$children.childrenOfChildren"
},
{
$group:{
_id:null,
maxPrice:{
$max:"$children.childrenOfChildren.price"
}
}
}
])
output:
{ "_id" : null, "maxPrice" : 110 }
try it online: mongoplayground.net/p/sBTclni0YSw
Upvotes: 4
Reputation: 16805
you can get maximum price from overall collection by using aggregate
query with $unwind
and $group
.
can try this query:
db.getCollection('collectionName').aggregate([
{$unwind: "$children"},
{$unwind: "$children.childrenOfChildren"},
{$group:{_id: null, price:{$max: "$children.childrenOfChildren.price"}}}
])
Upvotes: 1