Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get distinct results from a Mongoid criteria?

Tags:

mongoid

I am very frustrated as I try to query the results of a Mongoid criteria and keep only the documents where a field is distinct. And doing this:

Books.all.distinct(:name)

..only returns the name fields, not the documents.

Also using the uniq loop as stated in another question here does not work for me.

Books.all.uniq{|x| x.name} # Returns non-unique results

What am I missing here?

like image 879
picardo Avatar asked Jun 19 '12 21:06

picardo


People also ask

How do I get distinct records in MongoDB?

MongoDB – Distinct() Method In MongoDB, the distinct() method finds the distinct values for a given field across a single collection and returns the results in an array. It takes three parameters first one is the field for which to return distinct values and the others are optional.

How do I run a distinct query in MongoDB compass?

You can do this via aggregation framework in Compass, using $unwind and $group. The $unwind is performed to create a unique document for each element in the target array, which enables the $addToSet operator in the $group stage to then capture the genres as distinct elements.

How do you use distinct in Pymongo?

distinct() considers each element of the array as a separate value. For instance, if a field has as its value [ 1, [1], 1 ] , then db. collection. distinct() considers 1 , [1] , and 1 as separate values.

Which method calculates aggregate values for the data in a collection or a view?

aggregate() method is used to calculate aggregate values for the data in a collection. A sequence of data aggregation operations or stages.


1 Answers

OP, your problem is that you want every book with a unique name.

This issue with this is that lets say you have 98 unique books, and 2 books with the same name

If you ask your database: "Give me every uniquely named book" It will find the first 98 books, then it will run into the last two.

Which of the two books with the same name should it return? Since there's no right answer to this question given the level of detail, something like a hypothetical .uniq does not make sense.

like image 50
Hayk Saakian Avatar answered Oct 13 '22 21:10

Hayk Saakian