[英]How to retrieve top three documents based on inner array from MongoDB
我如何根据数组大小检索前三名文档, 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
}
首先,您需要添加$size
中的like
使用数组$addFields
,那么你可以很容易地$sort
,长度以获得前3名排序结果
db.collection.aggregate([
{
"$addFields": {
"likeLength": {
"$size": "$like"
}
}
},
{
"$sort": {
"likeLength": 1
}
},
{ "$limit": 3 }
])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.