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
>Solution :
To achieve this, you can use the MongoDB aggregation framework with a pipeline that has the following stages:
- $match: filter the documents to only include those with "val" equal to true.
- $group: group the documents by the "potential" field and create an array of unique values for each group using the $addToSet operator.
- $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!