简体   繁体   中英

How can I retrieve a mongodb collection using spring-data?

I want to retrieve List<Document> (as an example) of all documents in a MongoDB collection for given mongo shell query.

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;
    }
}

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> {

}

See example official on Product -> getAttributes() for more details visit Spring Data - Mongo DB

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM