find first of documents for each distinct values for one field

妖精的绣舞 提交于 2019-12-06 07:17:20

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
        }
    }
])

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!