0

I run the aggregate function to return the most liked items as follows:

db.users.aggregate(
    [
      { $unwind : "$favoriteItems" },
      { $group : { _id : "$favoriteItems" , number : { $sum : 1 } } },
      { $sort : { number : -1 } }
    ]
)

and this is a prototype document from my users collection

{
  "_id": "5a68a9308117670afc3522cd",
  "username": "user1",
  "favoriteItems": {
    "5a0c6711fb3aac66aafe26c6": {
      "_id": "5a0c6711fb3aac66aafe26c6",
      "name": "item1",
    },
    "5a0c6b83fd3eb67969316dd7": {
      "_id": "5a0c6b83fd3eb67969316dd7",
      "name": "item2",
    },
    "5a0c6b83fd3eb67969316de4": {
      "_id": "5a0c6b83fd3eb67969316de4",
      "name": "item3"
    }
  }
}

However, the aggregation function counts the favoriteItems as one single item and returns count per favoriteItems as opposed to elements in favoriteItems. what am I missing in the aggregate function?

0

1 Answer 1

2

You can try below aggregation in 3.4. As such $unwind works on the array not on document.

So use $objectToArray to transform object to array of key value pairs.

db.users.aggregate([
  {"$addFields":{"favoriteItems":{"$objectToArray":"$favoriteItems"}}},
  {"$unwind":"$favoriteItems"},
  {"$group":{"_id":"$favoriteItems.k","number":{"$sum":1}}},
  {"$sort":{"number":-1}}
])
Sign up to request clarification or add additional context in comments.

2 Comments

Thank a lot for the solution I fixed a small logical problem and it worked. Thank you so much again. I have one question: the does addFields alter the database or just the buffer used to process the documents?
Np. No aggregation doesn't alter the database.

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.