簡體   English   中英

如何從MongoDB中基於內部數組檢索前三個文檔

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM