如何从MongoDB中基于内部数组检索前三个文档

时间:2018-06-20 20:24:17

标签: javascript node.js 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
            }

1 个答案:

答案 0 :(得分:0)

您首先需要使用$size添加like数组的$addFields,然后可以轻松地按$sort的长度来获取前3个排序结果

db.collection.aggregate([
  {
    "$addFields": {
      "likeLength": {
        "$size": "$like"
      }
    }
  },
  {
    "$sort": {
      "likeLength": 1
    }
  },
  { "$limit": 3 }
])