查找集合Java Mongodb中的所有对象

编程入门 行业动态 更新时间:2024-10-26 23:30:01
本文介绍了查找集合Java Mongodb中的所有对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

下面的代码在集合中找到第一个文档:

Below code finds the first document in a collection :

package database; import com.mongodb.BasicDBObject; import com.mongodb.BulkWriteOperation; import com.mongodb.BulkWriteResult; import com.mongodb.Cursor; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; import com.mongodb.MongoClient; import com.mongodb.ParallelScanOptions; import com.mongodb.ServerAddress; import java.UnknownHostException; import java.util.List; import java.util.Set; import static java.util.concurrent.TimeUnit.SECONDS; // based on mongodb.github.io/mongo-java-driver/2.13/getting-started/quick-tour/ public class Mongo { public void getCon() { // or MongoClient mongoClient; try { mongoClient = new MongoClient("localhost", 27017); DB db = mongoClient.getDB("mydb"); DBCollection coll = db.getCollection("testCollection"); BasicDBObject doc = new BasicDBObject("name", "MongoDB") .append("type", "database") .append("count", 1) .append("info", new BasicDBObject("x", 203).append("y", 102)); coll.insert(doc); coll.findOne(); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }

似乎没有findAll方法.如何在集合testCollection中找到所有文档?

There does not appear to be a findAll method. How to find all the documents in the collection testCollection ?

推荐答案

您必须使用 DBCollection.find() 方法,

You have to use the DBCollection.find() method, which

选择集合中的所有文档,然后将光标移至所选文档.

Select all documents in collection and get a cursor to the selected documents.

所以,您要做的是:

DBCursor cursor = coll.find(); while (cursor.hasNext()) { DBObject obj = cursor.next(); //do your thing }

更多推荐

查找集合Java Mongodb中的所有对象

本文发布于:2023-11-29 22:11:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647773.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   Java   Mongodb

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!