Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find first of documents for each distinct values for one field

With a collection of documents with fields field1, field2, field3 and so on, I need to find

  1. distinct values for field3
  2. for each distinct value of field3, need to get the first document with each distinct value in field3

For # 1, I could do db.myCollection.distinct("field3")

How do I go about #2 ?

Sample Collection:

[
    { "field1": 11, "field2": "toyota", "field3": "camry" },
    { "field1": 22, "field2": "toyota", "field3": "corolla" },
    { "field1": 33, "field2": "toyota", "field3": "camry" },
    { "field1": 44, "field2": "honda", "field3": "accord" },
    { "field1": 55, "field2": "honda", "field3": "accord" },
    { "field1": 66, "field2": "honda", "field3": "city" }
]

Desired result:

[
    { "field1": 11, "field2": "toyota", "field3": "camry" },
    { "field1": 22, "field2": "toyota", "field3": "corolla" },
    { "field1": 44, "field2": "honda", "field3": "accord" },
    { "field1": 66, "field2": "honda", "field3": "city" }
]
like image 827
user3206440 Avatar asked Feb 17 '17 13:02

user3206440


People also ask

How can I get distinct values from a field in MongoDB?

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.

Where is first document in MongoDB?

MongoDB provides two methods for finding documents from a collection: findOne() - returns a the first document that matched with the specified criteria. find() - returns a cursor to the selected documents that matched with the specified criteria.

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.

What is aggregation in MongoDB?

What is Aggregation in MongoDB? Aggregation is a way of processing a large number of documents in a collection by means of passing them through different stages. The stages make up what is known as a pipeline. The stages in a pipeline can filter, sort, group, reshape and modify documents that pass through the pipeline.


2 Answers

You need to run an aggregate operation that groups all the documents by field3 and use the $first accumulator with the $$ROOT system variable to bring the first document, something like the following:

db.myCollection.aggregate([
    {
        "$group": {
            "_id": "$field3",
            "doc": { "$first": "$$ROOT" }
        }
    }
])

or for an exact output:

db.myCollection.aggregate([
    {
        "$group": {
            "_id": "$field3",
            "field1": { "$first": "$field1" },
            "field2": { "$first": "$field2" }
        }
    },
    {
        "$project": {
            "_id": 0,
            "field3": "$_id",
            "field2": 1,
            "field1": 1
        }
    }
])
like image 55
chridam Avatar answered Oct 12 '22 11:10

chridam


Aggregation groups records according to distinct values of field using $group aggregation operator

According to above mentioned description please try executing following query in MongoDB shell

db.myCollection.aggregate(

  // Pipeline
  [
    // Stage 1
    {
      $group: {
        _id:{field3:'$field3'},
        data:{$first:'$$ROOT'}
      }
    }

  ]


);

In above mentioned query data from the first document for each group is being fetched through use of $first aggregation operator and $$ROOT refers to document currently being processed through aggregation operation

like image 45
Rubin Porwal Avatar answered Oct 12 '22 13:10

Rubin Porwal