user15608655
user15608655

Reputation:

How to sort mongo docs with an array of elements by mongoose model

I am using mongodb and using mongoose to manipulate the database.

Here I have a set of docs that I would like to sort them by numbers of elements in the array.

Is there a way to sort them by its array length, in mongoose?

Below is an example of the db. I would like to sort them by the number of tags. OR by the number of likeBy (which is an array of userId)

enter image description here

Upvotes: 0

Views: 226

Answers (1)

J.F.
J.F.

Reputation: 15177

You can create an auxiliar field to sort by that field like this:

  • First $addFields to create the auxiliar field which value is the array size using $size.
  • Then sort by that value
  • And $project to not show the auxiliar field.
db.collection.aggregate({
  "$addFields": {
    "aux_size": {
      "$size": "$tags"
    }
  }
},
{
  "$sort": {
    "aux_size": 1
  }
},
{
  "$project": {
    "aux_size": 0
  }
})

Example here

Also, if you are using mongoose I think you won't need this because the model says tags fields must be an array. But in case the tags fields could be another type (string, number, boolean...) you can use $isArray to set that documents as length 0 (example here) or to filter them (example here)

Upvotes: 1

Related Questions