【问题标题】:How to get specific values of an embedded document Array in MongoDB using Java Driver如何使用 Java 驱动程序在 MongoDB 中获取嵌入式文档数组的特定值
【发布时间】:2017-03-10 17:56:13
【问题描述】:

我试图从数组中的每个嵌入文档中获取所有站点名称。我尝试使用以下语法但没有用

(网站.$.site)

{
  "user" : "username",
  "sites" : [{
      "sitename" : "site.com",
      "url" : "site.com",
      }, {
      "sitename" : "site2.com",
      "url" : "site2.com",
      },{
      "sitename" : "site2.com",
      "url" : "site2.com",
   }]
}

【问题讨论】:

标签: java mongodb


【解决方案1】:

Mongo-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" }

【讨论】:

  • 为什么你使用 Document 而不是 BasicDbObject ?我使用了 BasicDbObject 并做了一些更改。但它的工作原理谢谢
  • 从 mongodb3.0 开始 MongoCollection 插入、更新、查询、聚合和大多数方法只接受 org.bson.Document
猜你喜欢
  • 1970-01-01
  • 2019-05-27
  • 2023-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-22
  • 2015-08-17
  • 1970-01-01
相关资源
最近更新 更多