首页 > 解决方案 > 如何查询对象数组并仅返回与猫鼬匹配的对象

问题描述

我有下面的集合,想返回 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
        }
    }
]

标签: mongodbmongoose

解决方案


  1. $unwind- 从文档中解构数组
  2. $matchrounds.matches.firstParticipant.address- 按或rounds.matches.secondParticipant.address等于 789过滤文档。
  3. $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"
    }
  }
])

示例 Mongo Playground

输出

[
  {
    "firstParticipant": {
      "address": "789",
      "battlesWon": 0
    },
    "secondParticipant": {
      "address": "748569874",
      "battlesWon": 0
    }
  },
  {
    "firstParticipant": {
      "address": "258",
      "battlesWon": 0
    },
    "secondParticipant": {
      "address": "789",
      "battlesWon": 0
    }
  }
]

推荐阅读