2

Given data like

[
    { _id:1, data:["abc", "def", "hij", "klm", "nop"]},
    { _id:2, data:["abc", "def", "hij"]},
    { _id:3, data:["abc", "hij"]},
    { _id:4, data:["abc", "def", "hij", "klm", "nop"]},
    { _id:5, data:["def", "hij", "klm"]},
]

I am trying to get a query result like

[
    { "abc": 4 },
    { "def": 4 },
    { "hij": 5 },
    { "klm": 3 },
    { "nop": 2 },
]

where the number is the count of each data property array string value.

I have been working on it from an aggregate pipeline approach, but it seems like there should be an easier way.

3
  • Is that data available in javascript? would you accept an answer using javascript's array methods? Commented Jan 31, 2019 at 20:39
  • I have been working on constructing the query in the mongoDB CLI client, but the end goal environment is a nodejs app. I am using javascript Commented Jan 31, 2019 at 20:41
  • I can only offers a solution where you process the data on the Javascript side, but I believe you want it to comes already processed to Javascript. Anyway, I suggest to add what you have tried to far... Commented Jan 31, 2019 at 20:46

1 Answer 1

3

You ought to be able to do this with an aggregation pipeline with $unwind + $group. For example:

db.col.aggregate([{$unwind:"$data"}, {$group: {_id: "$data", data: {$sum: 1}}}])

Returns:

{ "_id" : "nop", "data" : 2.0 }
{ "_id" : "abc", "data" : 4.0 }
{ "_id" : "def", "data" : 4.0 }
{ "_id" : "hij", "data" : 5.0 }
{ "_id" : "klm", "data" : 3.0 }
Sign up to request clarification or add additional context in comments.

1 Comment

simply exactly. I found unwind's applicability moments after you posted this answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.