【问题标题】:how to get all the documents in collection from mongoDB using spring如何使用spring从mongoDB中获取所有文档
【发布时间】:2026-02-02 00:55:01
【问题描述】:

我试图从 mongoDB 的集合中获取所有文档,我正在使用 spring。

MongoTemplate  mongoOperation = SpringMongoConfig1.mongoTemplate()

在 monngoOperation 中,我没有找到任何从集合中返回所有文档的方法。 有人可以帮忙吗?

【问题讨论】:

标签: mongodb mongodb-query spring-data-mongodb


【解决方案1】:

如果要查找JavaDocumentName的所有文档(java中的任何集合名称)

List<JavaDocumentName> listRes = mongoOperation.findAll(JavaDocumentName.class);

【讨论】:

  • 如果 db 中有 1 亿条数据怎么办?我认为这会导致 OutOfMemory 错误。
【解决方案2】:

你可以这样做:

//If you don't need connection's configures. i.e. your mongo is in you localhost at 127.0.0.1:27017
MongoClient cliente = new MongoClient(); //to connect into a mongo DB

MongoDatabase mongoDb = client.getDatabase("DBname");  //get database, where DBname is the name of your database

MongoCollection<Document> robosCollection = mongoDb.getCollection("collectionName"); //get the name of the collection that you want

MongoCursor<Document> cursor =  robosCollection.find().cursor();//Mongo Cursor interface implementing the iterator protocol

    cursor.forEachRemaining(System.out::println); //print all documents in Collection using method reference

【讨论】:

    最近更新 更多