Daniel Turuș
Daniel Turuș

Reputation: 696

Mongoose - How to retrieve an array of objects from each document in collection?

Each document in my collection looks something like this (JSON):

{
name: "Roger",
matches: [
    {
        opponent: "Rafael Nadal",
        match_date: 1494536400000
    },
    {
        opponent: "Nick Kyrgyos",
        match_date: 1494557400000
    }
  ]
}

I want to extract all the matches each player had and also sort them by match_date using Mongoose, but I don't know how.

Could you please help me with this?

Upvotes: 1

Views: 49

Answers (1)

Ashh
Ashh

Reputation: 46451

You can try below aggregation

db.collection.aggregate([
  { "$unwind": "$matches" },
  { "$sort": { "matches.match_date": 1 }},
  { "$group": {
    "_id": "$_id",
    "matches": { "$push": "$matches" }
  }},
  { "$limit": 20 },
  { "$project": { "matches": 1, "numberOfMatches": { "$size": "$matches" } }}
])

Upvotes: 1

Related Questions