【问题标题】:How to display subdocuments in a document using the MongoDB Java driver如何使用 MongoDB Java 驱动程序在文档中显示子文档
【发布时间】:2018-01-24 04:36:48
【问题描述】:

鉴于这份文件:

Document{{
     _id=5a66fceba07b4ba90a19ee07, 
     address=Document{{
          building=8405,
          coord=[-74.02521709999999, 40.6224629],
          street=5 Avenue, zipcode=11209
     }},
     borough=Brooklyn, 
     cuisine=Chinese,
     grades=[
          Document{{date=Tue Feb 25 05:30:00 IST 2014,grade=A, score=12}},
          Document{{date=Wed Aug 14 05:30:00 IST 2013, grade=C, score=28}},
          Document{{date=Wed Jul 18 05:30:00 IST 2012, grade=A,score=13}}, 
          Document{{date=Fri Mar 09 05:30:00 IST 2012, grade=A, score=13}}, 
          Document{{date=Thu Oct 27 05:30:00 IST 2011, grade=A, score=12}},  
          Document{{date=Thu May 19 05:30:00 IST 2011, grade=A, score=13}}
     ],
     name=Chopstix Restaurant, restaurant_id=40900694
}}

我想在address字段中显示子文档。

如何使用 Java MongoDB 驱动程序 3.6.1 显示它?

【问题讨论】:

  • 能否请您格式化文档。

标签: java mongodb mongodb-query mongodb-java


【解决方案1】:

要使用 Mongo Java 驱动程序读取子文档(或文档的任何属性),请结合使用 Projectionscollection.find() ...

collection.find().projection(fields(include("x", "y"), excludeId()))

这是一个基于您问题中显示的文档的示例:

MongoClient mongoClient = ...;

MongoCollection<Document> collection = mongoClient.getDatabase(databaseName).getCollection(collectionName);

FindIterable<Document> documents = collection
        // create the predicates i.e. the 'where' clause
        .find(Filters.and(
                Filters.eq("address.street", "5 Avenue"),
                Filters.eq("address.zipcode", 11209),
                Filters.eq("cuisine", "Chinese")
        ))
        // create the projection(s) i.e. the select clause
        .projection(Projections.include("address"));

for (Document document : documents) {
    System.out.println(document.toJson());
}

更多详情in the docs,特别是标题为:

  • 投影字段
  • 使用查询过滤器获取单个文档
  • 通过查询获取一组文档

【讨论】:

    猜你喜欢
    • 2015-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-02
    • 2014-11-05
    • 2022-01-08
    • 1970-01-01
    相关资源
    最近更新 更多