简体   繁体   English

如何查询Java中的MongoDb子文档

[英]How to query MongoDb subdocuments in Java

Dear MongoDb Experts out there.尊敬的 MongoDb 专家。 I am new to Mongo and I am currently working with a MongoDb with Java.我是 Mongo 的新手,我目前正在使用 Java 使用 MongoDb。

Having a MongoDb with a collection called "teams" with the following example structure:拥有一个 MongoDb 和一个名为“teams”的集合,其示例结构如下:

{[
  {
    "id": "123",
    "name": "Dev1",
    "employees": [
      {"name": "John", "age": 30},
      {"name": "Jane", "age": 30}
    ]
  },
  {
    "id": "456",
    "name": "Dev2",
    "employees": [
      {"name": "Mike", "age": 30},
      {"name": "Oscar", "age": 27}
    ]
  }
]}

I want to have a query which returns an array with all employees, that are 30 years old.我想要一个查询,它返回一个包含所有 30 岁员工的数组。 So the expected result would be:所以预期的结果是:

{[
  {"name": "John", "age": 30},
  {"name": "Jane", "age": 30},
  {"name": "Mike", "age": 30}
]}

It would be even better to only get the employees name (since I know the age I searched for), like:最好只获取员工姓名(因为我知道我搜索的年龄),例如:

{[
  {"name": "John"},
  {"name": "Jane"},
  {"name": "Mike"}
]}

I have a MongoCollection object:我有一个 MongoCollection object:

MongoCollection<Document> collection = mongoClient
    .getDatabase(databaseName)
    .getCollection("teams")

My question: Is it possible to retrieve my expected result from the MongoDb?我的问题:是否可以从 MongoDb 检索我的预期结果? If so, which operations do I have to call on my collection object?如果是这样,我必须对我的集合 object 调用哪些操作?

Approach 1: Find with $elemMatch projection方法 1:使用 $elemMatch 投影查找

db.getCollection('teams').find(
      {"employees.age":30},
      { "employees": { "$elemMatch": { "age": 30 } },"_id":0 } 
)

Output Format: Output 格式:

{
    "employees" : [ 
        {
            "name" : "John",
            "age" : 30.0
        }
    ]
}


{
    "employees" : [ 
        {
            "name" : "Mike",
            "age" : 30.0
        }
    ]
}

Approach 2: Aggregate with $unwind and key renaming using $projection方法 2:使用 $unwind 聚合并使用 $projection 重命名键

db.getCollection('teams').aggregate([
       {"$match": {"employees.age":30}} ,  
       {"$unwind":  "$employees"},
       {"$match": {"employees.age":30}} ,
       {"$project": {"name": "$employees.name","_id":0}}
])

Output format: Output 格式:

{
    "name" : "John"
}


{
    "name" : "Jane"
}


{
    "name" : "Mike"
}

Approach 1 would be faster, but require additional work at app layer.方法 1 会更快,但需要在应用层进行额外的工作。 It is recommended to offload formatting tasks to app servers rather than on db itself.建议将格式化任务卸载到应用服务器而不是数据库本身。

Approach 2 can instantly give to the formatted results, doing the querying and formatting both in the database servers方法 2 可以立即给出格式化结果,在数据库服务器中进行查询和格式化

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM