These are chat archives for Automattic/mongoose

29th
Nov 2017
Tom
@goto1
Nov 29 2017 15:38
thanks for your help @vladotesanovic, it works beautifully!
Vlado Tesanovic
@vladotesanovic
Nov 29 2017 18:54
@goto1 :beer:
Arye Shalev
@pantchox
Nov 29 2017 19:47
Hi everyone, i need your advice on an issue i am not sure of.
I have a collection of documents lets say articles, and each document (Article) has a field of "tags" type "[String]". that string array fields hold the IDs of the tags collection, for example tags: ["11", "22", "33"] where each of these ids are (of course mongo object id) referring to the tags collection documents which has the tag name and some other stuff.
Now what i need to do is to count for each tag how many articles (documents) are using that specific tag.
Any idea how to do this? i saw some map reduce examples but it was more accumulating examples rather then grouping, i am a bit lost.. apperciate any feedback! thanks
Vlado Tesanovic
@vladotesanovic
Nov 29 2017 20:50
@pantchox
Articles.count({ tags: { $in: ['22'] }  })
Arye Shalev
@pantchox
Nov 29 2017 22:14
@vladotesanovic thanks i will look into that but that mean that if i want to know for all my tags collection i need to do
Tags.find({}, (err, tags) => { tags.forEach((tag) => Articles.count({tags: { $in: [tag] } }) ) ; } )
Vlado Tesanovic
@vladotesanovic
Nov 29 2017 22:18
@pantchox ah, you don't have that info than... Yes... If you want to do it in one call than you need '$group' operator within aggregation
Arye Shalev
@pantchox
Nov 29 2017 22:19
any guidelines regarding this? i like mongoose i find mongoDB examples confusing my logic
Vlado Tesanovic
@vladotesanovic
Nov 29 2017 22:30
@pantchox it is not easy put you have YourModel.aggregate function n mongoose
db.notes.aggregate(

    // Pipeline
    [
        // Stage 1
        {
            $unwind: { path: "$tags" }
        },

        // Stage 2
        {
            $group: { 
              _id : "$tags", 
              docs: { $push: "$title" }, 
              count: { $sum: 1 }  
            }
        },

    ]

);
this aggregate solves your problem :D
it will be something like this
Articles.aggregate([
 {
    $unwind: { path: "$tags" }
 },
 {
            $group: { 
              _id : "$tags", 
              docs: { $push: "$title" }, 
              count: { $sum: 1 }  
            }
 },
])
more or less execute above code and you will get what you need @pantchox
Arye Shalev
@pantchox
Nov 29 2017 22:42
wow! many thanks for you investment in time to help me with this
:)
will try to implement it now