简体   繁体   中英

How to retrieve top three documents based on inner array from MongoDB

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
            }

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 }
])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM