andrescabana86
andrescabana86

Reputation: 1788

make one array of multiple arrays in javascript with mongodb

i have this structure in my mongodb

    {
        category:['A','B'],
        info:.....,
    }
    {
        category:['A','F','T'],
        info:.....,
    }
    {
        category:['A','C'],
        info:.....,
    }
    {
        category:['D','B'],
        info:.....,
    }

i have to query all categories,

var db = mongo.db(read+"@127.0.0.1:27017/database",{safe:false});
db.collection('comercio').find({},{_id:0,'category.$':1},function(err, result_array)

first question, there is any way to get all categories?? an other aproach instead of mine??

second question....

i have to make an array that contains all categories but not repeat any category... in this example i have to make an array that contains this...

all_categories=['A','B','C','D','F','T'];

thank you all again...

Upvotes: 2

Views: 218

Answers (2)

Asya Kamsky
Asya Kamsky

Reputation: 42352

You don't need aggregation framework to get back an array of distinct categories.

Just use distinct:

> db.comercio.distinct("category");
["A","B","C","D","F","T"]

Upvotes: 1

Silver_Clash
Silver_Clash

Reputation: 405

You must use Aggregation framework for this query, like this:

db.comercio.aggregate( { $unwind : "$category" } );

After unwind you can use other aggregations (e.g. group) to get what you need.

Upvotes: 1

Related Questions