英文:
How can I retrieve a mongodb collection using spring-data?
问题
我想检索给定mongo
shell查询中MongoDB集合中的所有文档的List<Document>
(作为示例)。
英文:
I want to retrieve List<Document>
(as an example) of all documents in a MongoDB collection for given mongo
shell query.
答案1
得分: 2
以下是您要翻译的内容:
您可以在不将“Document”映射到域模型的情况下检索集合。
不确定您正在追求的目的是什么,但这里有一个示例:
package com.answers.stackoverflow.spring.mondbretrievedata.data;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoCollection;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.ArrayList;
import java.util.List;
@Repository
public class MongoRepository {
private static final String DatabaseName = "EXAMPLE";
private static final String CollectionName = "example";
@Autowired
private MongoClient client;
public List<String> allDocuments() {
final List<String> list = new ArrayList<>();
final MongoCollection<Document> data = client.getDatabase(DatabaseName).getCollection(CollectionName);
data.find().map(Document::toJson).forEach(list::add);
return list;
}
}
英文:
You can retrieve a collection without mapping Document
to a domain model.
Not sure whats the purpose you are chasing, but here you have an example:
package com.answers.stackoverflow.spring.mondbretrievedata.data;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoCollection;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.ArrayList;
import java.util.List;
@Repository
public class MongoRepository {
private static final String DatabaseName = "EXAMPLE";
private static final String CollectionName = "example";
@Autowired
private MongoClient client;
public List<String> allDocuments() {
final List<String> list = new ArrayList<>();
final MongoCollection<Document> data = client.getDatabase(DatabaseName).getCollection(CollectionName);
data.find().map(Document::toJson).forEach(list::add);
return list;
}
}
答案2
得分: 0
当您使用MongoRepository
时,您必须提供一个PersistentEntity
。因此,请使用您的模型类,该模型类将由MongoRepository
扩展:
public interface YOUR_MODEL_Repository extends MongoRepository<MODEL_CLASS, String> {
}
英文:
When you use the MongoRepository
, you have to give a PersistentEntity
. So use your model class which is to be extended by MongoRepository
public interface YOUR_MODEL_Repository extends MongoRepository<MODEL_CLASS, String> {
}
答案3
得分: -1
请查看Product -> getAttributes()的官方示例,以获取更多详细信息,请访问Spring Data - Mongo DB。
英文:
See example official on Product -> getAttributes() for more details visit Spring Data - Mongo DB
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论