首页 > 解决方案 > MongoDB- 按 id 查找文档,然后用键对其进行分组

问题描述


我的数据结构如下所示:

[
  {
    "_id": "1",
    "title": "Yamaha",
    "data": "Sed ut perspiciatis",
    "type": "Bike"
  },
  {
    "_id": "2",
    "title": "Pulsar",
    "data": "Quis autem vel eum",
    "type": "Bike"
  },
  {
    "_id": "3",
    "title": "Tesla Model Y",
    "data": "because it is pleasure",
    "type": "Car"
  },
  {
    "_id": "4",
    "title": "Harley-Davidson",
    "data": "praising pain was born",
    "type": "Bike"
  },
  {
    "_id": "6",
    "title": "Mustang",
    "data": "non numquam eius",
    "type": "Car"
  },
  {
    "_id": "7",
    "title": "BMW",
    "data": "Man of Culture",
    "type": "Car"
  }
]

现在,来自前端的用户可以使用他们的唯一性搜索数据库中的任何项目,如下所示:_id

db.collection.find({_id: "3" })

它返回以下内容:

[
  {
    "_id": "3",
    "data": "because it is pleasure",
    "title": "Tesla Model Y",
    "type": "Car"
  }
]

问题部分:

现在,包括上面返回的文档,我也想返回那些具有匹配值的文档。type


我的问题意味着;如果用户正在查找任何带有其特定_id. 让我们假设3那么它应该返回以下内容:

查找具有唯一性_id字段$group的项目type

  [{
    "_id": "3",
    "title": "Tesla Model Y",
    "data": "because it is pleasure",
    "type": "Car"
  }
  {
    "_id": "6",
    "title": "Mustang",
    "data": "non numquam eius",
    "type": "Car"
  },
  {
    "_id": "7",
    "title": "BMW",
    "data": "Man of Culture",
    "type": "Car"
  }]

那有可能吗?$group之后的文件有可能finding By Id吗?我已经尝试了几种方法来做到这一点,但每种方法都没有用。对于这个复杂的要求,任何建议都会有所帮助

:)

标签: mongodbaggregation-framework

解决方案


询问

  • 用它自己查找,只加入 id=3 具有的类型。
  • 空连接结果 => 不同类型,因此它们被过滤掉

测试代码在这里

db.collection.aggregate([
  {
    "$lookup": {
      "from": "collection",
      "let": {
        "type": "$type"
      },
      "pipeline": [
        {
          "$match": {
            "$expr": {
              "$and": [
                {
                  "$eq": [
                    "$_id",
                    "3"
                  ]
                },
                {
                  "$eq": [
                    "$$type",
                    "$type"
                  ]
                }
              ]
            }
          }
        }
      ],
      "as": "joined"
    }
  },
  {
    "$match": {
      "$expr": {
        "$ne": [
          "$joined",
          []
        ]
      }
    }
  },
  {
    "$unset": [
      "joined"
    ]
  }
])

推荐阅读