0

I have an aggregation like this :

this.collection.aggregate([
      {
        "$match": {
          _id: id
        }
      },
      {
        "$addFields": {
          "self": "$$ROOT"
        }
      },
      {
        "$graphLookup": {
          "from": "posts",
          "startWith": "$_id",
          "connectFromField": "_id",
          "connectToField": "postId",
          "as": "postLookup"
        }
      },
      {
        "$addFields": {
          "postLookup": {
            "$concatArrays": [
              "$postLookup",
              [
                "$self"
              ]
            ]
          }
        }
      },
      {
        "$lookup": {
          "from": "comments",
          "localField": "postLookup._id",
          "foreignField": "postId",
          "as": "commentsLookup"
        }
      },
      {
        "$project": {
          children: {
            posts: {
              "$map": {
                "input": "$postLookup",
                "as": "c",
                "in": "$$c._id"
              }
            },
            comments: {
              "$map": {
                "input": "$commentsLookup",
                "as": "t",
                "in": "$$t._id"
              }
            }
          }
        }
      }
    ]);

So the expected result is supposed to be like this:

{
   children: {
        posts: {
            Array
          },
        comments: {
            Array
          }
}
}

The problem is that the aggregation function returns a cursor which can not be converted to an array because it's not a list of documents, it's an object in which you can find inside it the arrays. I couldn't get these two arrays from the cursor itself.. Can someone guide me on what i'm missing here. Thanks

Sara
  • 5
  • 3
  • maybe you are looking for this: https://stackoverflow.com/questions/38577895/iterate-over-mongodb-cursor-from-aggregate/38578824 – R2D2 Jan 08 '22 at 00:17
  • No, that's not what i'm looking for. The object returned by the aggregation is not transformable to an array. ``` { children: { posts: { Array }, comments: { Array } } } ``` foreach would have to run on cursor.children.categories.forEach: which can not be done by just accessing it via the cursor.children. My question is how to get cursor.chilrdren.categories[i] ... and cursor.children.templates[i].. – Sara Jan 08 '22 at 14:55
  • Did you try using the `.toArray()` method of the cursor? – Joe Jan 09 '22 at 08:06
  • THat's what im saying in the question exactly. I tried.toArray() but the structure in the mongo query inside project: it's not an array and that's why .toArray don't work. Because the structure of the returned cursor is an object containing two arrays. Does anyone know how to get that object from the returned cursor – Sara Jan 10 '22 at 16:16

0 Answers0