Matias Bertoni
Matias Bertoni

Reputation: 498

Is there a way to limit an array but know the length of the array without limiting it?

I want to limit a query and get its total length in mongoose

like this:

comment: [1,2,3,4,5,6,7,8,9,10] //length 10

const comments = await CommentModel.find().limit(3).count() //this does not work;

console.log(comments)
output:

{ length: 10, comments: [1, 2, 3] }

thanks a lot.

Upvotes: 0

Views: 61

Answers (1)

J.F.
J.F.

Reputation: 15225

You can use the project object into the query like this:

db.collection.find({},
{
  "_id": 0,
  "comment": {
    "$slice": 3
  },
  "length": {
    "$size": "$comment"
  }
})

Example here where the output is:

[
  {
    "comment": [
      1,
      2,
      3
    ],
    "length": 10
  }
]

Upvotes: 1

Related Questions