我试图从阵列中的每个嵌入式文档获取所有的网站名称。我尝试使用以下语法,但没有工作
(网站。$。网站)
{
"user" : "username",
"sites" : [{
"sitename" : "site.com",
"url" : "site.com",
}, {
"sitename" : "site2.com",
"url" : "site2.com",
},{
"sitename" : "site2.com",
"url" : "site2.com",
}]
}
答案 0 :(得分:1)
蒙戈-java的,
MongoClient mongoClient = new MongoClient("localhost",27017);
MongoDatabase database = mongoClient.getDatabase("Test");
MongoCollection<Document> collection = database.getCollection("collection");
ArrayList<Document> doc = new ArrayList<Document>();
doc.add(new Document().append("$unwind","$sites"));
doc.add(new Document().append("$project",new Document().append("sitename","$sites.sitename")));
List<Document> results =collection.aggregate(doc).into(new ArrayList<Document>());
for(Document res: results){
System.out.println(res.toJson());
}
输出:
{ "_id" : { "$oid" : "58c26ce044400b08ca6ff483" }, "sitename" : "site.com" }
{ "_id" : { "$oid" : "58c26ce044400b08ca6ff483" }, "sitename" : "site2.com" }
{ "_id" : { "$oid" : "58c26ce044400b08ca6ff483" }, "sitename" : "site2.com" }