MongoDB
 sql >> Database >  >> NoSQL >> MongoDB

ordina la raccolta mongo in base al punteggio dei documenti figlio

Puoi provare sotto l'aggregazione.

db.editors.aggregate([
  {"$lookup":{
    "from":"books",
    "localField":"_id",
    "foreignField":"parentId",
    "as":"books"
  }},
  {"$unwind":"$books"},
  {"$match":{"books.type":"sci-fi"}},
  {"$group":{
    "_id":"$_id",
    "name":{"$first":"$name"},
    "scores":{"$sum":"$books.score"}
  }},
  {"$sort":{"scores":-1}},
  {"$limit":10}
])
db.editors.aggregate([
  {"$lookup":{
    "from":"books",
    "localField":"_id",
    "foreignField":"parentId",
    "as":"books"
  }},
  {"$project":{
    "name":1,
    "scores":{"$sum":"$books.score"}
  }},
  {"$sort":{"scores":-1}}
])