【问题标题】:MongoDB query and select inner objectMongoDB查询并选择内部对象
【发布时间】:2018-12-19 06:56:34
【问题描述】:

我想查询内部对象并从 mongoddb 文档中仅选择过滤的内部对象。

考虑下面的 mongodb 文档。

{
  "schools": [
    {
      "name": "ABC",
      "students": [
        {
          "name": "ABC 1",
          "class": 1
        },
        {
          "name": "ABC 2",
          "class": 2
        },
        {
          "name": "ABC 3",
          "class": 1
        }
      ]
    },
    {
      "name": "XYZ",
      "students": [
        {
          "name": "XYZ 1",
          "class": 1
        },
        {
          "name": "XYZ 2",
          "class": 2
        }
      ]
    }
  ]
}

我只想选择班级 1 的学生。 预期结果 json 如下。

{
  "school": {
    "name": "ABC",
    "students": [
      {
        "name": "ABC 1",
        "class": 1
      },
      {
        "name": "ABC 3",
        "class": 1
      }
    ]
  },
  "school": {
    "name": "XYZ",
    "students": [
      {
        "name": "XYZ 1",
        "class": 1
      }
    ]
  }
}

即使下面的结果对我来说也很好。

{
  "students": [
    {
      "name": "ABC 1",
      "class": 1
    },
    {
      "name": "ABC 3",
      "class": 1
    },
    {
      "name": "XYZ 1",
      "class": 1
    }
  ]
}

请帮助我完成这项工作。 如果可以提供 mongodb 查询真的很有帮助。 我在我的应用程序中使用 mongodb 和 spring 数据。

【问题讨论】:

  • db.myCollection.find({"school.students.class":1});试试
  • 是学校文档的数组吗?
  • 如果 school 是一个对象并且有多个 school 对象,那么它应该是一个 school 对象数组?
  • 是的。我相应地编辑了json。在最初的问题中,我粘贴了错误的 json。现在我更正了。

标签: java mongodb mongodb-query aggregation-framework spring-data-mongodb


【解决方案1】:

您可以搜索 mongo db 数组嵌套记录搜索。示例代码在这里。 Document is here.

db.your_collection_name.find({'school.student.class':1})

如果您只希望学生为您的结果制作平面图。 Here is document for flatmap in mongodb

【讨论】:

  • 是的。这是过滤我的收藏。但它返回整个集合。我只想要学生的子列表。
  • 我添加了有关从列表中选择子列表的文档。
  • 感谢您的帮助。 .你能帮我使用 unwind with query 来解决我的问题吗?
【解决方案2】:

我终于可以找到查询了。 首先,我必须放松并应用匹配标准。这对我有用。

db.{mycollection}.aggregate(
    [
        { $unwind: '$schools.students'}, 
        { $match : { "schools.students.class" : 1 } }, 
        { $project : { "schools.name" : 1, 'schools.students' : 1 }  } 
    ] 
);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-14
    • 1970-01-01
    • 2020-03-14
    • 1970-01-01
    • 2022-11-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多