我有以下 mongo db 架构,我正在尝试构建一个聚合查询,该查询在 github_open_issues
键下的 repo
下搜索,并且可以返回与 {{1} 的所有值的匹配项} 作为值。我已经尝试了以下作为我的查询,但它没有返回任何结果。我有点困惑为什么这不起作用,因为我有另一个具有类似于此架构的数据库,并且这种类型的查询在那里工作,但这里似乎有些不同并且不起作用。我还整理了这个交互式示例 mongoplayground
repoA
db.collection.aggregate([
{
"$unwind": "$github_open_issues"
},
{
"$match": {
"github_open_issues.repo": {
"$in": [
"repoA"
]
}
}
},
])
答案 0 :(得分:2)
$objectToArray
将 github_open_issues
对象转换为键值格式的数组$filter
迭代上述转换数组的循环并过滤您的搜索条件$match
过滤 github_open_issues
不为空$arrayToObject
将 github_open_issues
数组转换为对象db.collection.aggregate([
{
$addFields: {
github_open_issues: {
$filter: {
input: { $objectToArray: "$github_open_issues" },
cond: { $in: ["$$this.v.repo", ["repoA"]] }
}
}
}
},
{ $match: { github_open_issues: { $ne: [] } } },
{ $addFields: { github_open_issues: { $arrayToObject: "$github_open_issues" } } }
])
答案 1 :(得分:0)
您的查询是正确的,但架构中的数据在 github_open_issues.repo 中放置错误,您的对象按{"0": {values... }, "1" 之类的数字放置:{values... }} 无法获得您想要的值。您现在可以查看游乐场playground