Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Mongodb, grouping values only once

I am new to mongodb, I have a collection of people and some of them have a value that I am interested in ("val"). For everyone who has that value, I would like to have a list of another value ("potential") without repeating.

{ "_id" : 001, "val" : true, "potential", 100}
{ "_id" : 002, "val" : true, "potential", 200}
{ "_id" : 003, "val" : true, "potential", 200}
{ "_id" : 004, "potential" : 300}
{ "_id" : 005, "potential" : 400}

I would like to get

{"values" : [100, 200]}

Thank you very much

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

To achieve this, you can use the MongoDB aggregation framework with a pipeline that has the following stages:

  1. $match: filter the documents to only include those with "val" equal to true.
  2. $group: group the documents by the "potential" field and create an array of unique values for each group using the $addToSet operator.
  3. $project: reshape the output to return only the array of "potential" values.
    Here’s an example of the MongoDB aggregation pipeline:
db.collection.aggregate([
  {
    $match: { val: true }
  },
  {
    $group: {
      _id: null,
      potentials: { $addToSet: "$potential" }
    }
  },
  {
    $project: {
      _id: 0,
      values: "$potentials"
    }
  }
])

This will return a document with a single field "values" containing an array of unique "potential" values for documents with "val" equal to true:

{ "values" : [100, 200] }

I hope this helps!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading