javascript - 如何根据 MongoDB 的内部数组检索前三个文档

标签 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
            }

最佳答案

您需要先添加$size使用 $addFieldslike 数组,那么您就可以轻松$sort与长度以获得前 3 个排序结果

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

关于javascript - 如何根据 MongoDB 的内部数组检索前三个文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50956488/

相关文章:

javascript - 在 Azure 函数中运行 Playwright

node.js - Expressjs 的 Jade 路径解析

javascript - 使用 Javascript 获取下一个和上一个 MongoDB

mongodb - Windows 10 Pro 的 Cassandra 和 MongoDB 最低系统要求

javascript - 将 jquery 与从 Angular 动态创建的元素一起使用不起作用

javascript - 高阶函数(如 .map())如何在 JavaScript 内部工作?

javascript - 在javascript中用两个点调用号码方法?

javascript - node.js、socket.io、__dirname 路由问题

node.js - Mongoose :子文档 CastError:转换为数组失败

arrays - mongodb 模式如何为子文档数组设置默认值?