鉴于此文件:
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显示它?
答案 0 :(得分:0)
要使用Mongo Java驱动程序读取子文档(或文档的任何属性),请将Projections
与collection.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,特别是标题为:
的部分