So lets start by inserting some products in to our collection:
db.products.insertMany([
{ name: 'TV', tags: ['livingroom', 'electronics']},
{ name: 'Radio', tags: ['bedroom', 'electronics']},
{ name: 'Computer', tags: ['bedroom', 'electronics']}
]);
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("586bae0ec5a9a94b2674943d"),
ObjectId("586bae0ec5a9a94b2674943e"),
ObjectId("586bae0ec5a9a94b2674943f")
]
}
We can now write a simple aggreation query to go though all the documents
db.products.aggregate([
{$unwind: '$tags'},
{$group: {_id: '$tags' }},
{$out: 'productTags'}
]);
The {$unwind: '$tags'}
will deconstruct the tags array field in to a document for each tag.
Then the {$group: {_id: '$tags' }}
will group each item and create a new document for each tag.
Then the {$out: 'productTags'}
will create us a productTags collection with the output of the documents.
now if we query the productTags
collection we'll get the following output:
> db.productTags.find()
{ "_id" : "bedroom" }
{ "_id" : "electronics" }
{ "_id" : "livingroom" }