mongodbmongomapper

mongodb. how to select distinct records


I need to get documents only with distinct values

SQL should be something like this: SELECT DISTINCT engine_type_id FROM cars But I have no idea how to get same behaviour in the mongo.

Thank in advance.

P.S. I tried to use mongo's distinct method, but it returns array of distinct engine_type_id instead of whole documents. So it's doesn't work for me unfortunately.


Solution

  • We can use distinct method with 2 arguments.

    Here is how I get all ids: ids = db.cars .distinct("_id", "engine_type_id")

    Next I can hit db with next query: db.cars.find({"_id": {$in: ids}})

    So, that's all!

    For those, who using ruby with MongoMapper, please take a look here:

    ids = MongoMapper.database.eval("db.cars.distinct('_id', 'engine_type_id'})")
    Car.where(_id: { :$in => ids })