How does mongodb sort by array length?

  mongodb, question

1. The following data are available

I want to sort in descending order according to the size of the content array.

It means that the line’ general worker/operator’ is at the front and the line’ numerical control programming’ is at the back.

I used it.sort({'this.content.length':-1})Andsort({'content.$size':-1})It turned out to be no good.

It is possible to take the array length in real time and then sort it, but the efficiency is very poor, because indexes cannot be used to speed up at all. It is almost unacceptable when there is a large amount of data. The more recommended way is to update the array length to a field by the way when updating the array, build an index on this field, and then sort by this field.
If you insist on using the former, you need to use it$size

 {$ project: {size: {$ size: "$ content"}, < other required fields >}}},
 {$sort: {size: -1}}
 ], {allowDiskUse: true})