2017-09-26 42 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看看我的第二篇文章。 –