gpt4 book ai didi

javascript - Mongoose:find() - 匹配两个值并仅返回匹配的文档

转载 作者:行者123 更新时间:2023-12-03 01:12:37 27 4
gpt4 key购买 nike

我环顾四周,找不到解决这个问题的确切方法。我浏览了 Mongoose 文档并试图找到一种方法。我是 MongoDB 的新手,在学习了很多教程后,我希望能够制作自己的 API。

目标:

http://localhost:3000/seasons/19/1 的 GET 请求并返回系列详细信息 19 和所选剧集 1

类似于:

{
"_id": "5b893aff76c12c166c4e75ae",
"season_number": 19,
"name": "Season 19",
"number_of_episodes": 24,
"episode": [
{
"_id": "5b895e56089a9a152c16af1f",
"episode_number": 1,
"name": "19.01",
"length": "1:23:33",
"author": "Aaron Wright",
"release": "2018-01-13T00:00:00.000Z",
"description": "We kick off our 2018 season with the worst of CES and the future of smart toilets before Aaron unravels the controversial “Dear David” saga that has sparked controversy. We then look at state sponsored mind control programs and the hypnotic experiments performed on unwitting Princeton students in the 1960s."
},

}

问题:

我似乎无法弄清楚如何仅使用选定的一集返回上述对象。由于所有数据都在episodes中,但如果我手动使用episodes[0]等,我可以返回它。

这是存储库文件,因此不要让这篇文章太长: https://github.com/DannnB/mysterious-universe-api/blob/master/api/controllers/seasons.js

  • :63
  • 名称:seasons_get_episode_number

感谢您的帮助!

数据库 - 托管在 MongoDB Atlas - 免费套餐,因此无法使用 $where 并且不想使用 $where因为它是一个繁重的命令。

 "data": [
{
"_id": "5b893aff76c12c166c4e75ae",
"season_number": 19,
"name": "Season 19",
"number_of_episodes": 24,
"episodes": [
{
"_id": "5b895e56089a9a152c16af1f",
"episode_number": 1,
"name": "19.01",
"length": "1:23:33",
"author": "Aaron Wright",
"release": "2018-01-13T00:00:00.000Z",
"description": "We kick off our 2018 season with the worst of CES and the future of smart toilets before Aaron unravels the controversial “Dear David” saga that has sparked controversy. We then look at state sponsored mind control programs and the hypnotic experiments performed on unwitting Princeton students in the 1960s."
},
{
"_id": "5b895fee089a9a152c16af20",
"episode_number": 2,
"name": "19.02",
"length": "1:22:11",
"author": "Benjamin Grundy",
"release": "2018-01-20T00:00:00.000Z",
"description": "This week we unravel the cosmic serpent to find the origins of life and the link between DNA and Ayahuasca visions. Could the building blocks of all life also be a conscious force that is capable of direct communication with our altered states of mind?"
}
]
},
{
"_id": "5b893b2276c12c166c4e75b0",
"season_number": 20,
"name": "Season 20",
"number_of_episodes": 9
}, *and so on...*
]

最佳答案

您可以使用聚合上可用的$filter运算符。以下是符合您要求的查询:

db.seasons.aggregate([
{ "$match": { "season_number": 19 } },
{ "$project": {
"season_number": 1,
"name": 1,
"number_of_episodes": 1,
"episodes": {
"$filter": {
"input": "$episodes",
"as": "episode",
"cond": { "$eq": [ "$$episode.episode_number", 1 ] }
}
}
}
}])

$filter 从版本 3.2 开始可用

关于javascript - Mongoose:find() - 匹配两个值并仅返回匹配的文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52151345/

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