recoba78
recoba78

Reputation: 99

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.

Upvotes: 0

Views: 6074

Answers (3)

someoneigna
someoneigna

Reputation: 556

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

Upvotes: 2

sercheo_87
sercheo_87

Reputation: 873

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

Upvotes: -1

varman
varman

Reputation: 8894

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

}

Upvotes: 0

Related Questions