How to get non-duplicate records with mongoDB and Morphia?

2

How do I get mongoDB to return a list of non-duplicate documents.

In my case, the mongoDB returns a list of ingredients from all the recipes registered, but I want those records without duplication because the recipes can repeat the same ingredients. How can I solve this problem?

List<Datasheet> datasheets = 
            getDatastore().find(Datasheet.class).retrievedFields(true, "ingredients").asList();
    
asked by anonymous 06.05.2016 / 19:32

2 answers

0

I was able to solve the problem using the Google GSON library. I just added the lib jar to use the methods.

Follow the code:

public List<Ingredient> listIngredients() throws Exception {

    // Para usar o distinct tivemos que utilizar o getCollection
    List ingredientsDB = getDatastore().getCollection(Datasheet.class).distinct("ingredients");
    List<Ingredient> ingredients = new ArrayList<>();

    // Como a lista vinda do banco é DBObject tivemos que usar a lib Gson para atribuir o JSON a lista de ingredientes
    Gson gson = new Gson();
    for (int i = 0; i < ingredientsDB.size(); i++) {
        ingredients.add(gson.fromJson(ingredientsDB.get(i).toString(), Ingredient.class));
    }

    return ingredients;
}//listIngredients
    
19.05.2016 / 02:47
0

If you want to know only the distinct values for a particular field in a set of documents in a collection, you can use the distinct. db.collection.distinct (field, query).

However if you want to return a set of distinct 'documents' for a given field, in which case you should use MapReduce, or aggregate, it will depend on your need.

MongoDB is a 'dumb' bank, it does little logic for you, in case you search for separate documents for a field, you need some logic to exclude documents that should not be returned and MongoDB does not offer a logic of this natively, plus offers a means by which you can implement that is by using db.collection.mapReduce. link

    
17.05.2016 / 19:20