代码之家  ›  专栏  ›  技术社区  ›  Daniel Turuș

Mongoose-如何从集合中的每个文档检索对象数组?

  •  1
  • Daniel Turuș  · 技术社区  · 6 年前

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

    我想提取每个球员的所有比赛,并对他们进行排序 match_date

    1 回复  |  直到 6 年前
        1
  •  1
  •   Ashh    6 年前

    你可以在下面试试

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