Blank
Blank

Reputation: 443

mongodb - aggregation - nested object

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?

Upvotes: 0

Views: 1620

Answers (1)

s7vr
s7vr

Reputation: 75934

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}}
])

Upvotes: 2

Related Questions