如何根据like
数组大小检索前三名文档,如以下来自MongoDB的响应所示?我正在使用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
}
答案 0 :(得分:0)
您首先需要使用$size
添加like
数组的$addFields
,然后可以轻松地按$sort
的长度来获取前3个排序结果
db.collection.aggregate([
{
"$addFields": {
"likeLength": {
"$size": "$like"
}
}
},
{
"$sort": {
"likeLength": 1
}
},
{ "$limit": 3 }
])