Home > Software design >  mongoDB Compass distinct query renders no results
mongoDB Compass distinct query renders no results

Time:05-31

I've been trying to write a distinct query against my mongoDB collection housed in Atlas.

I wanted to get a list of all the distinct values captured within the "Section" attribute under its "MetaData" parent attribute. According to the mongoDB documentation the syntax to get an array of distinct values is the following syntax:

{ distinct: "<collection>", key: "<field>" }

My sample collection called "simple" holds the following documents

[{
  "_id": "527c61082241f813c09c722c",
  "MetaData": {
    "Type": "BlogPost",
    "Author": "author1",
    "Section": "section1"
  },
  "Title": "title 1",
  "Description": "..."
},
{
  "_id": "527c61082241f813c09c7050",
  "MetaData": {
    "Type": "BlogPost",
    "Author": "author1",
    "Section": "section1"
  },
  "Title": "title 2",
  "Description": "..."
},
{
  "_id": "527c61082241f813c09c7042",
  "MetaData": {
    "Type": "BlogPost",
    "Author": "author1",
    "Section": "section2"
  },
  "Title": "title 3",
  "Description": "..."
  }
]

yet when I execute the following filter query in Compass or Atlas's - no results are returned ???

 {distinct: 'simple',key: 'MetaData.Section'}

I was expecting an array holding "section1" and "section2"

Can someone tell what I'm doing incorrectly please
Thanks

CodePudding user response:

You need to use aggregation framework for compass to get distinct values

{
   $group:{
     "_id": null,
     "sections": { $addToSet: "$MetaData.Section"}
   }
}
  • Related