mongodb - 为什么我的结果数组在这个 mongo 查询中返回为空?
问题描述
这是我的查询,我是 Mongo 的新手,所以我有点摸索这个查询。我的目标是让球员的队友得到供应。我将显示查询,然后显示播放器的文档。
db.Players.aggregate([{
$match: {_id: "/players/c/cruzne02.shtml"}},
{$unwind: "$teams"},
{$unwind: "$teams.years"},
{$lookup: {
from: "Players",
let: {team_name: "$teams.name", team_year: "$teams.years"},
pipeline: [{
$match: {
$expr: {
$and: [
{$eq: ["$teams.name", "$$team_name"]},
{$eq: ["$teams.years", "$$team_year"]},
]
}
},
}],
as: "results"
}},
{$unwind: {
path: "$results",
preserveNullAndEmptyArrays: true
}},
{$group: {
_id: {
team: "$teams.name",
year: "$teams.years"
},
results: {
$push: "$results"
}
}},
{$project: {
team: "$_id.team",
year: "$_id.year",
results: 1,
_id: 0
}}
]);
{
"_id": "/players/c/cruzne02.shtml",
"url": "/players/c/cruzne02.shtml",
"name": "Nelson Cruz",
"image": "https://www.baseball-reference.com/req/202108020/images/headshots/f/fea2f131_mlbam.jpg",
"teams": [{
"name": "MIL",
"years": [2005]
}, {
"name": "TEX",
"years": [2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013]
}, {
"name": "BAL",
"years": [2014]
}, {
"name": "SEA",
"years": [2015, 2016, 2017, 2018]
}, {
"name": "MIN",
"years": [2019, 2020, 2021]
}, {
"name": "TBR",
"years": [2021]
}]
}
我可以取回该组,但结果数组始终为空。团队和年份排成一列,但结果永远不会出现。我当前的结果有空数组,我需要更改什么。
编辑:这是我的结果
[ { results: [], team: 'MIN', year: 2020 },
{ results: [], team: 'TEX', year: 2006 },
{ results: [], team: 'MIL', year: 2005 },
{ results: [], team: 'TEX', year: 2008 },
{ results: [], team: 'TBR', year: 2021 },
{ results: [], team: 'SEA', year: 2018 },
{ results: [], team: 'TEX', year: 2007 },
{ results: [], team: 'MIN', year: 2019 },
{ results: [], team: 'SEA', year: 2017 },
{ results: [], team: 'TEX', year: 2013 },
{ results: [], team: 'TEX', year: 2011 },
{ results: [], team: 'TEX', year: 2012 },
{ results: [], team: 'SEA', year: 2016 },
{ results: [], team: 'TEX', year: 2010 },
{ results: [], team: 'SEA', year: 2015 },
{ results: [], team: 'BAL', year: 2014 },
{ results: [], team: 'MIN', year: 2021 },
{ results: [], team: 'TEX', year: 2009 } ]
解决方案
放在$match
聚合的末尾。
db.collection.aggregate([
{
$unwind: "$teams"
},
{
$unwind: "$teams.years"
},
{
$group: {
_id: {
team: "$teams.name",
year: "$teams.years",
},
results: {
$push: {
"name": "$name",
"id": "$_id"
}
}
}
},
{
$match: {
"results.id": "/players/c/cruzne02.shtml"
}
}
])
推荐阅读
- vba - 带有日期函数的 for/if 循环问题
- html - 从网页中的输入标签中提取元素信息
- r - 是否有用于反转数字向量内容符号的 R 函数?
- unit-testing - Microsoft.Extensions.Logging.Abstractions 更新后 Moq 和 Microsoft.Extensions.Logging.ILogger 单元测试失败
- reactjs - React 防止子组件重新渲染
- python - 嵌套列表理解与嵌套 for 循环不同
- sql-server - Making XMLA/DAX requests to ISS/SSAS
- python - 从相机保存视频得到语法错误
- amazon-web-services - Amazon Linux (RedHat/CentOS) EC2 上的 openpyxl "BadZipFile"
- java - Java 应用程序中更多的线程是否会增加 CPU% 的使用率并降低应用程序的速度?