title: Query with aggregate, graphLookup and pipeline in mongoDb
body: <p>I have to manage a wall with comments, each wall have many parent comments and each parent comment have child comments.</p>
  
  <p>my collection <strong>walls</strong> is like this</p>
  
  <pre><code> groupId : {type: Schema.Types.ObjectId, ref: 'groups', unique: true},
      comments : [{
          commentId : {type: Schema.Types.ObjectId, ref: 'comments'},
          memberId : {type: Schema.Types.ObjectId, ref: 'members'},
      }],
  </code></pre>
  
  <p>and the collection <strong>comments</strong> is like this </p>
  
  <pre><code>text : String,
  parentCommentId : {type: Schema.Types.ObjectId, ref: 'comments', default : null},
  </code></pre>
  
  <p>I want to display my wall by parent comments, each child comment under its parent comment.</p>
  
  <p>but the result in mongo db isn't sorted all times, the sort seems to be random,</p>
  
  <p>1- How to sort the childs array with field (childs.createdAt)</p>
  
  <p>2- How to display only these fields under childs (_id / date / createdAt) and these fields (_id / childs / date) under array comments</p>
  
  <p><strong>query</strong> </p>
  
  <pre><code>db.walls.aggregate([
    {
      $lookup: {
        from: "comments",
        let: {
          commentIds: "$comments.commentId"
        },
        pipeline: [
          {
            $match: {
              $expr: {
                $in: [
                  "$_id",
                  "$$commentIds"
                ]
              },
              parentCommentId: null
            }
          },
          {
            $graphLookup: {
              from: "comments",
              startWith: "$_id",
              connectFromField: "parentCommentId",
              connectToField: "parentCommentId",
              as: "childs"
            }
          }
        ],
        as: "comments"
      }
    }
  ])
  </code></pre>
  
  <p><strong>data</strong></p>
  
  <p><a href="https://mongoplayground.net/p/XTu0yeLTMMr" rel="nofollow noreferrer">https://mongoplayground.net/p/XTu0yeLTMMr</a></p>
  
  <p>How can i modify my query ? thank you.</p>