2017-09-26 38 views
-1

就像我有三個字段'到','從'和'消息',我只是想顯示消息字段的內容,我在其中給出了一些子句。 文獻{{_ ID = 59c7d57c674cd5673c304936,爲= 9915103230,來自= 9915103229,日期= 24/12/2017年,消息= HELLO WORLD}}如何從mongoDB中只提取一個值?

只想RETRIEVE的 「Hello World」,而不是整個文檔。

就像我只想要的那樣,String message = ????? --->我在這裏需要一些方法,所以String類型的變量獲取值Hello World。

投影方法不適用於我。

我正在使用JDBC MongoDB 3.5驅動程序。

+1

問題是,我們不能幫你一個爛攤子,沒有輸入/輸出,也沒有任何努力的跡象 –

+0

[只能返回文檔\ _id在mongoose .find()]上(https://stackoverflow.com/questions/46284659/only-return-document-id -on-貓鼬找到的)。您可以使用[Projection](https://docs.mongodb.com/manual/reference/method/db.collection.find/#find-projection)。我在我的答案中解釋了一些如何使用它。 – zero298

+0

@ zero298我做了你的實現,但它沒有工作,或者我錯誤地實現了,因爲我是mongoDB的新手,我在「等待」時出錯 - 我不記得確切的錯誤信息。謝謝。 – Ratik

回答

0

這裏的一個起作用PROG編譯靠在3.5驅動

 MongoClient mongoClient = new MongoClient(); 
     MongoDatabase db = mongoClient.getDatabase("testX"); 
     MongoCollection<BsonDocument> coll = db.getCollection("foo", BsonDocument.class); 
     coll.drop(); 

     { 
      BsonDocument doc = new BsonDocument(); 
      doc.put("from", new BsonInt32(23343223)); 
      doc.put("to", new BsonInt32(23343223)); 
      doc.put("msg", new BsonString("hello")); 
      coll.insertOne(doc); 

      doc.remove("_id"); 
      doc.put("from", new BsonInt32(8889)); 
      doc.put("to", new BsonInt32(99999)); 
      doc.put("msg", new BsonString("goodbye")); 
      coll.insertOne(doc); 
     } 

     { 
      BsonDocument query = new BsonDocument("from", new BsonInt32(8889)); 
      BsonDocument proj = new BsonDocument("msg", new BsonInt32(1)); 
      proj.put("_id",new BsonInt32(0)); 

      BsonDocument d2 = coll.find(query).projection(proj).first(); 
      System.out.println(d2); 

      String s2 = coll.find(query).projection(proj).first().getString("msg").getValue(); 
      System.out.println(s2); 
     } 
1

使用投影,find()的第二個可選參數。對於上下文,這給你整個文檔:

db.yourCollection.find({到:9915103230,從:9915103229});

這給你只有結果的消息。僅舉領域並將其設置爲1:

db.yourCollection.find({到:9915103230,來自:9915103229},{消息:1};

您可以指定多個件事返回:

db.yourCollection.find({到:9915103230,從:9915103229},{消息:1,於:1};

+0

也可以通過傳遞'_id:0'來壓制'_id'字段 –

+0

請再次看到我的問題。我試過你的東西,但它不工作。謝謝。 – Ratik

+0

@Ratik看看我的第二篇文章。 –