mongodb - 如何查询对象数组并仅返回与猫鼬匹配的对象
问题描述
我有下面的集合,想返回 firstParticipant.address 或 secondParticipant.address = 789 的所有匹配项 如何使用猫鼬进行此查询并仅返回与过滤器匹配的对象?
我的文件:
{
"_id": "25113",
"title": "Jogo de futebol",
"rounds": {
"matches": [{
"firstParticipant": {
"address": "789",
"battlesWon": 0
},
"secondParticipant": {
"address": "748569874",
"battlesWon": 0
}
},
{
"firstParticipant": {
"address": "963",
"battlesWon": 0
},
"secondParticipant": {
"address": "741",
"battlesWon": 0
}
},
{
"firstParticipant": {
"address": "258",
"battlesWon": 0
},
"secondParticipant": {
"address": "789",
"battlesWon": 0
}
}
]
}
}
预期结果:
[{
"firstParticipant": {
"address": "789",
"battlesWon": 0
},
"secondParticipant": {
"address": "748569874",
"battlesWon": 0
}
},
{
"firstParticipant": {
"address": "258",
"battlesWon": 0
},
"secondParticipant": {
"address": "789",
"battlesWon": 0
}
}
]
解决方案
$unwind
- 从文档中解构数组$match
rounds.matches.firstParticipant.address
- 按或rounds.matches.secondParticipant.address
等于 789过滤文档。$replaceRoot
- 将输入文档替换为$rounds.matches
.
db.collection.aggregate([
{
$unwind: "$rounds.matches"
},
{
$match: {
$or: [
{
"rounds.matches.firstParticipant.address": {
$eq: "789"
}
},
{
"rounds.matches.secondParticipant.address": {
$eq: "789"
}
}
]
}
},
{
$replaceRoot: {
newRoot: "$rounds.matches"
}
}
])
输出
[
{
"firstParticipant": {
"address": "789",
"battlesWon": 0
},
"secondParticipant": {
"address": "748569874",
"battlesWon": 0
}
},
{
"firstParticipant": {
"address": "258",
"battlesWon": 0
},
"secondParticipant": {
"address": "789",
"battlesWon": 0
}
}
]
推荐阅读
- java - Keycloak 适配器 pkix 路径构建失败
- firebase-realtime-database - 如何在单个活动中检索不同的子 Firebase 数据库
- c++ - C ++:释放构造函数中所需的障碍,该构造函数创建访问构造对象的线程
- java - 通过多部分请求直接将文件上传到 FileInputStream 的 Jetty 文件
- java - 有 1 个数据节点正在运行,并且在此操作中排除了 1 个节点。(伪分布式模式)
- microsoft-graph-api - Microsoft Graph - 最近的端点不返回最近使用的文件
- android - 如何获取 itemView 追星族回收站视图
- javascript - 在wordpress中导入脚本
- string - 如何将字符串(具有固定分隔符)转换为要附加到 JSON 的数组?
- visual-studio - 创建自定义 TFS 用户并授予/拒绝其权限