Eleonora Ciceri
Eleonora Ciceri

Reputation: 1798

MongoDB: distinct tuples

Suppose to have a collection of MongoDB documents with the following structure:

{
    id_str:     "some_value",
    text:       "some_text",
    some_field: "some_other_value"
}

I would like to filter such documents so as to obtain the ones with distinct text values.

I learned from the MongoDB documentation how to extract unique field values from a collection, using the distinct operation. Thus, by performing the following query:

db.myCollection.distinct("text")

I would obtain an array containing the distinct text values:

["first_distinct_text", "second_distinct_text",...]

However, this is not the result that i would like to obtain. Instead, I would like to have the following:

{ "id_str": "a_sample_of_id_having_first_distinct_text", 
  "text": "first_distinct_text"}
{ "id_str": "a_sample_of_id_having_second_distinct_text", 
  "text": "second_distinct_text"}

I am not sure if this can be done with a single query.

I found a similar question which, however, do not solve fully my problem.

Do you have any hint on how to solve this problem?

Thanks.

Upvotes: 2

Views: 2120

Answers (2)

Etienne Membrives
Etienne Membrives

Reputation: 879

You should look into making an aggregate query using the $group stage, and probably using the $first operator.

Maybe something along the lines of:

db.myCollection.aggregate([{ $group : { _id : { text: "$text"},
                                        text: { $first: "$id_str" }
                                      }
                           }])

Upvotes: 2

viktor.svirskyy
viktor.svirskyy

Reputation: 479

try:

 db.myCollection.aggregate({$group: {_id: {'text': "$text", 'id_str': '$id_str'}}})

More information here: http://docs.mongodb.org/manual/reference/method/db.collection.aggregate/

Upvotes: 0

Related Questions