user1569050
user1569050

Reputation: 6367

MongoDB aggregate array

Say I have a MongoDB collection with documents like—

{
  "name": "Hawaiian",
  "toppings": ['cheese', 'ham', 'pineapple'],
}

How could I get a list of all the collection's toppings?

I assume I'd have to use MapReduce or the new aggregation framework (ideally MapReduce as I can't use the new aggregation framework), but I'm not sure how to do it.

Thanks!

Edit: And, is there a way to count the number of distinct toppings at the database level?

Upvotes: 2

Views: 559

Answers (3)

nickmilon
nickmilon

Reputation: 1372

distinct will work for a limited number of unique items (<=50k?)

if more than that you got to use mapreduce

fun_map ="""function () for (e in this.toppings) { emit (entities.toppings[e],1); } """

fun_reduce = """function (key, values) {var total = 0; for (var i = 0; i < values.length; i++) { total += values[i]; } return total;}""" then you call

collection.map_reduce(fun_map,fun_reduce,out={"replace":'your_outputcollection_name"}, full_response=True)

your topings items will be the _id of your output collection while value will represent a count of each particula toping

Upvotes: 1

JohnnyHK
JohnnyHK

Reputation: 312129

You can use a distinct query for that:

db.coll.distinct('toppings')

Upvotes: 1

user1480400
user1480400

Reputation:

MongoDB supports DISTINCT aggregation. This should do the trick.

Upvotes: 1

Related Questions