title: Updating field to a sorted nested array field
body: <p>I have a document of the collection <strong>Topic</strong> that has the following nested array</p>
  <pre><code>[
    {
      _id: ObjectId(&quot;618c6718c6a8cc3a84a0b37f&quot;),
      subscribers: [ 
       {userId: ObjectId(&quot;618c643545f4ecd43e9b20f7&quot;), points: {daily: 50, total: 100} }, 
       {userId: ObjectId(&quot;618c641345f4ecd43e9b20f0&quot;), points: {daily: 10, total: 80} }, 
       {userId: ObjectId(&quot;618c648c45f4ecd43e9b20fc&quot;), points: {daily: 20, total: 80} }
      ],
      quizzes: [],
      leaderboards: {
        daily: [],
        total: []
      },
    }
  ]
  </code></pre>
  <p>Is there anyway to sort the subscribers list by daily points and set the results to the nested daily array in leaderboards field?</p>
  <p>I.e I wish my document will look like this after the query</p>
  <pre><code>[
    {
      _id: ObjectId(&quot;618c6718c6a8cc3a84a0b37f&quot;),
      subscribers: [ 
       {userId: ObjectId(&quot;618c643545f4ecd43e9b20f7&quot;), points: {daily: 20, total: 70} }, 
       {userId: ObjectId(&quot;618c641345f4ecd43e9b20f0&quot;), points: {daily: 10, total: 60} }, 
       {userId: ObjectId(&quot;618c648c45f4ecd43e9b20fc&quot;), points: {daily: 15, total: 50} }
      ],
      quizzes: [],
      leaderboards: {
        daily: [
         {userId: ObjectId(&quot;618c643545f4ecd43e9b20f7&quot;), points: {daily: 20, total: 70} },
         {userId: ObjectId(&quot;618c648c45f4ecd43e9b20fc&quot;), points: {daily: 15, total: 50} } 
         {userId: ObjectId(&quot;618c641345f4ecd43e9b20f0&quot;), points: {daily: 10, total: 60} }, 
         
      ],
        total: []
      },
    }
  ]
  </code></pre>
  <p>I was able to find the following code</p>
  <pre><code>db.collection.aggregate(
  { $unwind: &quot;$memberships&quot; },
  { $sort: { &quot;memberships.price&quot;: 1 }},
  { $group: {
      _id: &quot;$_id&quot;,
      &quot;memberships&quot;: { $push: &quot;$memberships&quot; }
    }
  })
  </code></pre>
  <p>from <a href="https://stackoverflow.com/questions/62345528/mongoose-sort-nested-array-of-object-not-working">Mongoose sort nested array of object not working</a></p>
  <p>This aggregation works, but it sorts <strong>subscribers</strong> rather than using the resulting array to update the <strong>daily</strong> nested field.</p>