How to get duplicated records with mongoDB and Morphia?

Asked

Viewed 515 times

2

How do I get mongoDB to return me a list of un-duplicated documents.

In my case mongoDB returns a list of ingredients from all registered recipes, but I want these 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();

2 answers

0


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

Follows 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

0

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

However if you want to return a set of separate 'documents' for a given field, in this case you must use Mapreduce, or Aggregate, it will depend on your need.

Mongodb is a 'donkey' bank, it makes little logic for you, in case of searching distinct documents for a field, it is necessary some logic to delete documents that should not be returned and Mongodb does not offer a logic like this natively, more offers a means by which you can implement which is using db.collection.mapReduce. https://docs.mongodb.com/v3.0/reference/method/db.collection.mapReduce/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.