Here's my MongoDB collection:
{
"_id" : ObjectId("515d8f53175b8ecb053425c2"),
"category" : "Batteries",
"products" : [
{
"brand" : "Duracell",
"item" : [
"AA",
"AAA"
]
},
{
"brand" : "Everyday",
"item" : [
"9V",
"AA",
"12V"
]
}
]
}
The output that I need is
1) Unique list of all items
{["AA", "AAA", "9V", "12V"]}
and 2. unique list of items per product
{
"category" : "Batteries",
"item": ["AA", "AAA", "9V", "12V"]
}
I'm very new to MongoDB, and I tried different aggregations functions and nothing seems to work. Please help.
To get unique values and ignore duplicates, use distinct() in MongoDB. The distinct() finds the distinct values for a specified field across a single collection and returns the results in an array.
In MongoDB, the distinct() method finds the distinct values for a given field across a single collection and returns the results in an array. It takes three parameters first one is the field for which to return distinct values and the others are optional.
The pipeline provides efficient data aggregation using native operations within MongoDB, and is the preferred method for data aggregation in MongoDB. The aggregation pipeline can operate on a sharded collection. The aggregation pipeline can use indexes to improve its performance during some of its stages.
After few more tries, I had solved this. Here's the commands:
db.xyz.aggregate( {$project: {a: '$products.item'}},
{$unwind: '$a'},
{$unwind: '$a'},
{$group: {_id: 'a', items: {$addToSet: '$a'}}});
and
db.xyz.aggregate( {$project: {category: 1, a: '$products.item'}},
{$unwind: '$a'},
{$unwind: '$a'},
{$group: {_id: '$category', items: {$addToSet: '$a'}}});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With