Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pivoting data in MongoDB

I have an 'articles' collection, some sample data might look like this:

[
{body: 'Interesting news in Siberia and so on etc. etc. etc. and lolcats too',
author: 'John Doe',
tags: [{tid:24, name: "Siberia"}, 
       {tid: 5231, name: "Lolcats"},]
},
{body: 'Something is going on in Siberia and France',
author: 'Jane Doe',
tags: [{tid:24, name: "Siberia"}, 
       {tid: 6432, name: "France"},]
},
]

And my required ouput is a distinct list of tags:

[
{tid: 24, name: 'Siberia'},
{tid: 5231, name: 'Lolcats'},
{tid: 6432, name: 'France'},
]

I have been struggling with some mapReduce queries and distinct aggregation, but without result.

like image 981
Bagvendt Avatar asked Jul 29 '26 20:07

Bagvendt


1 Answers

The simplest way to do this is:

db.articles.distinct("tags")

If you want to use aggregation framework (new in 2.2) it's a little longer:

db.articles.aggregate([{$unwind:"$tags"}, 
                   {$group:{_id:"$tags"}},
                   {$project:{tid:"$_id.tid",name:"$_id.name",_id:0}}
]).result
like image 168
Asya Kamsky Avatar answered Aug 01 '26 13:08

Asya Kamsky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!