gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 01:47:24 24 4
gpt4 key购买 nike

如何根据 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com