Group and retain only a few fields in a MongoDB query

Viewed 77

I'm kinda new to Mongo and I'm facing some difficulties trying to retrieve and filter my data

My collection entries look like :

{_id:object, "field1":"value1", "field2":"value2", [...], "field n":"value n"}

I'm currently doing this query to only retrieve the necessary fields :

db;collection.aggregate({$project:{_id:"field1",field2:1}})

Which works and return

{_id:"value1", "field2":"value2"}

However, I'm getting way too much duplicated entries, so I'd like _id to be unique. I saw there is a distinct() function but it can't be used with aggregate, so is there a way to do it using groups maybe ?

Have you any idea about how could I do ?

EDIT:

What I have :

[ { "_id" : ObjectId("5ebbf0e90cf269611e3d34a1"), "libelle" : "Libelle for 2903", "code" : "_2903" },
{ "_id" : ObjectId("5ebd39b90cf20c0ce837a51b"), "libelle" : "Libelle for 2903", "code" : "_2903" },
{ "_id" : ObjectId("5ebbcc0d0cf20c0ce8379819"), "libelle" : "Libelle for 15027", "code" : "_15027" },
{ "_id" : ObjectId("5eba930c0cf20c0ce83779bf"), "libelle" : "Libelle for 15027", "code" : "_15027" } ]

What I want my query to return :

[ { "_id" : "_2903", "libelle" : "Libelle for 2903" },
{ "_id" : "_15027", "libelle" : "Libelle for 15027" } ]
1 Answers

You need to use project

db.collection.aggregate([
  {
    "$project": {
      _id: 1,
      field2: 1
    }
  }
])

This helps to remove or add fields.. Projection


Update 1

db.collection.aggregate([
  {
    "$group": {
      "_id": "$rncp",
      "libelle": {
        "$first": "$libelle"
      }
    }
  }
])

Working Mongo playground

Related