2017-08-24 96 views
0

的一些屬性的JSON文件假設一個MongoCollection有2個文件如下圖所示獲取基於JSON

{"employee_id": "1", {"name":"A","age":"18"}} 

{"employee_id": "2", {"name":"B","age":"18"}} 

我如何可以查詢此集合,使得其將返回我的第一篇文檔僅使用employee_id

使用以下Maven條目

 <dependency> 
      <groupId>org.mongodb</groupId> 
      <artifactId>mongodb-driver</artifactId> 
      <version>3.5.0-alpha1</version> 
     </dependency> 

回答

1

您提供的示例文檔不是有效的JSON;他們似乎包含兩個值"1"{"name":"A","age":"18"}但只有一個鍵:"employee_id"

假設...

  • 有效的文檔格式是:

    {"employee_id": "1", "details": {"name":"A","age":"18"}} 
    
  • 您正在尋找指導使用蒙戈Java驅動程序(這個假設是基於你的Maven的的包容該司機的座標)。

然後,下面的代碼說明了如何通過過濾上employee_id查找第一文檔:

@Test 
public void canRead() { 
    MongoClient mongoClient = new MongoClientFactory().create(); 

    MongoCollection<Document> collection = mongoClient.getDatabase("stackoverflow").getCollection("sample"); 

    // this test assumes that the two documents you showed in your question have already been written to the collection e.g. 
    // collection.insertOne(Document.parse("{\"employee_id\": \"1\", \"details\": {\"name\":\"A\",\"age\":\"18\"}}")); 
    // collection.insertOne(Document.parse("{\"employee_id\": \"2\", \"details\": {\"name\":\"B\",\"age\":\"18\"}}")); 

    Bson filter = Filters.eq("employee_id", "1"); 
    Assert.assertEquals(1, collection.count(filter)); 

    Document document = collection.find(filter).first(); 
    Assert.assertEquals("1", document.get("employee_id")); 
    Document details = (Document) document.get("details"); 
    Assert.assertEquals("A", details.get("name")); 
    // age is a string?! 
    Assert.assertEquals("18", details.get("age")); 
}