1

im trying to get count of documents based on array of element. My collection have documents like...

[
   {pid: "p001", items :["apple","bat","cat"]},
   {pid: "p002", items :["apple","cat","bat"]},
   {pid: "p003", items :["apple","bat","cat","dog"]},
   {pid: "p004", items :["apple","bat","cat","dog"]}
]

i write a mongo aggregation query like

db.collection_name.aggregate([
   {$group : {_id: "$items", count: {$sum : 1}}},
   {$project : { _id: 0, items: "$_id" , count: 1 } }
])

im getting output like

[
   {items: ["apple","bat","cat"], count: 1},
   {items: ["apple","cat","bat"], count: 1},
   {items: ["apple","bat","cat","dog"], count: 2}
]

but i want my output like

[
    {items: ["apple","bat","cat"], count: 2},
    {items: ["apple","bat","cat","dog"], count: 2}
]

can you help me out of this.....

1 Answer 1

1

You need to $sort the items array in order to make it similar to the other items array and then can $group with the items

db.collection.aggregate([
  { "$unwind": "$items" },
  { "$sort": { "items": 1 }},
  { "$group": { "_id": "$pid", "items": { "$push": "$items" }}},
  { "$group": { "_id": "$items", "count": { "$sum": 1 }}},
  { "$project": { "_id": 0, "items": "$_id", "count": 1 }}
])
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.