sql >> Base de Datos >  >> NoSQL >> MongoDB

Cómo ordenar, seleccionar y consultar subdocumentos en mongoose

Puedes cambiar tu $project para remodelar también la salida para proporcionar la estructura que está buscando:

Story.aggregate([
    { $unwind: "$comments" },
    { $project: {
        author: '$comments.author',
        content: '$comments.content',
        _id: '$comments._id'
    }},
    { $sort: {author: -1}}
], function (err, result) { ...

Salida:

[ { _id: 541c2776149002af52ed3c4a,
    author: 'B author',
    content: '2 Content' },
  { _id: 541c2776149002af52ed3c4b,
    author: 'A author',
    content: '1 Content' } ]