-1
 Problem.aggregate(
    [
      { $unwind: "$comments" },
      {
        $group: {
          _id: "$_id",
          size: { $size: "$comments" }
        }
      }
    ],
    function(err, results) {
      console.log(err);
      console.log(results);
    }
  );

I tried to use $size with aggregation, but I get this error:

MongoError: unknown group operator '$size'.

I am using mongodb version 3.6. I just want to get the length of the comments attribute which is an array.

Here is a sample problem document:

{
    "_id": {
        "$oid": "5e02a2184a6e7f4980f47e8f"
    },
    "author": {
        "id": {
            "$oid": "5e027a4badd90919304a9eb0"
        }
    },
    "description": "testd",
    "gender": 0,
    "dailyUpvotes": 2,
    "tags": [
        {
            "_id": {
                "$oid": "5e02a2184a6e7f4980f47e90"
            },
            "name": "test"
        }
    ],
    "title": "test",
    "upVotes": 2,
    "comments": [
        {
            "_id": {
                "$oid": "5e03124933c17d406471d6f9"
            },
            "id": {
                "$oid": "5e03124933c17d406471d6f8"
            }
        }
    ],
    "upVotesList": [
        {
            "_id": {
                "$oid": "5e045a07745eb94b584d27e1"
            },
            "userID": {
                "$oid": "5e045a00745eb94b584d27e0"
            }
        },
        {
            "_id": {
                "$oid": "5e02a26b3cbe4e3794555f42"
            },
            "userID": {
                "$oid": "5e027a4badd90919304a9eb0"
            }
        }
    ],
    "createdAt": {
        "$date": "2019-12-24T23:41:12.707Z"
    },
    "updatedAt": {
        "$date": "2019-12-26T06:58:15.080Z"
    },
    "__v": 2
}

Instead of getting the array of , I just want to get the length of the array. If there is another way that does not use aggregation, that would be fine too :) Thanks in advance!

3

1 Answer 1

1

Try something like this.

Problem.aggregate([
   {
      $project: {
         item: 1,
         numberOfResults: { $size: "$comments" }
      }
   }
] )

take alook at https://docs.mongodb.com/manual/reference/operator/aggregation/size/

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.