Reputation: 93
How can I retrieve the top three docs based on like
array size as shown in the below response from MongoDB? I am using Node.js.
"status": true,
"data": [
{
"tags": [
"IoT"
],
"fileUrls": [
"www.miraclesoft1.com",
"www.miraclesoft2.com"
],
"createdDate": "2018-06-18T14:45:17.651Z",
"_id": "5b27e57116e7821bd0b2a0f3",
"title": "Ide hub testing7",
"description": "Meet Aditi - The Co-ordinator Bot with Amazon Alexa and AWS Lambda Meet Aditi - The Co-ordinator Bot with Amazon Alexa and AWS Lambda",
"category": "Development",
"ideaStatus": "false",
"createdByLoginId": "rkanumetta",
"createdByName": "Rajesh Kumar Kanumetta",
"like": [],
"comments": [],
"__v": 0
},
{
"tags": [
"IoT"
],
"fileUrls": [
"www.miraclesoft1.com",
"www.miraclesoft2.com"
],
"createdDate": "2018-06-18T14:45:17.651Z",
"_id": "5b27e57516e7821bd0b2a0f4",
"title": "Ide hub testing8",
"description": "Meet Aditi - The Co-ordinator Bot with Amazon Alexa and AWS Lambda Meet Aditi - The Co-ordinator Bot with Amazon Alexa and AWS Lambda",
"category": "Development",
"ideaStatus": "false",
"createdByLoginId": "rkanumetta",
"createdByName": "Rajesh Kumar Kanumetta",
"like": [],
"comments": [],
"__v": 0
}
Upvotes: 1
Views: 64
Reputation: 46471
You need to first add the $size
of the like
array using $addFields
, then you can easily $sort
with the length to get the top 3 sorted result
db.collection.aggregate([
{
"$addFields": {
"likeLength": {
"$size": "$like"
}
}
},
{
"$sort": {
"likeLength": 1
}
},
{ "$limit": 3 }
])
Upvotes: 1