Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a list of all unique tags in mongodb

Tags:

I am beginning with mongodb and have a collection with documents that look like the following

{
    "type": 1,
    "tags": ["tag1", "tag2", "tag3"]
}
{
    "type": 2,
    "tags": ["tag2", "tag3"]
}
{
    "type": 3,
    "tags": ["tag1", "tag3"]
}
{
    "type": 1,
    "tags": ["tag1", "tag4"]
}

With this, I want a set of all the tags for a particular type. For example, for type 1, I want the set of tag1, tag2, tag3, tag4 (any order).

All I could think of is to get the tags and add them to a set in python, but I wanted to know if there is a way to do it with mongodb's mapreduce or something else. Please advise.

like image 481
sharat87 Avatar asked Feb 12 '11 05:02

sharat87


People also ask

What's a good way to get a list of all unique tags for a collection of documents millions of items large when we doesn't have access to MongoDB new distinct command?

What's the best way to keep track of unique tags for a collection of documents millions of items large? The normal way of doing tagging seems to be indexing multikeys.

How do I get unique records in MongoDB?

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.

Which command gives all the distinct values in MongoDB?

MongoDB – Distinct() Method 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.

What does find () do in MongoDB?

Find() Method. In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents.


1 Answers

If you just want a (distinct) list of the tags then using distinct will be best. Map/Reduce will be slower and can't use an index for the javascript part.

http://docs.mongodb.org/manual/reference/method/db.collection.distinct/

db.coll.distinct("tags", {type:1}) Will return a set of tags for type=1.

like image 110
Scott Hernandez Avatar answered Oct 07 '22 15:10

Scott Hernandez