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?
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.
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.
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.
aggregate() method is used to calculate aggregate values for the data in a collection. A sequence of data aggregation operations or stages.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With