2

So I'm trying to sort subdocument, but also select and everything. It seems I can't with a regular query so I tried w/ aggregate

mongoose = require("mongoose");
mongoose.connect("localhost:27017", function(err) {
  mongoose.connection.db.dropDatabase();
  Story = mongoose.model("Story", {
    title: String,
    comments: [{
      author: String,
      content: String
    }]
  });
  sample = new Story({
    title: "Foobar",
    comments: [
    {
      author: "A author",
      content: "1 Content"
    },
    {
      author: "B author",
      content: "2 Content"
    }
    ]
  });
  sample.save(function(err, doc) {
    Story.aggregate([
        { $match: {
            _id: doc._id
        }},
        { $unwind: "$comments" },
        { $project: {"comments": 1}},
        { $sort: {"comments.author": -1}}
    ], function (err, result) {
        if (err) {
            console.log(err);
            return;
        }
        console.log(result);
    });
  })
});

This almost work:

[ { _id: 541c0f8098f85ac41c240de4,
    comments:
     { author: 'B author',
       content: '2 Content',
       _id: 541c0f8098f85ac41c240de5 } },
  { _id: 541c0f8098f85ac41c240de4,
    comments:
     { author: 'A author',
       content: '1 Content',
       _id: 541c0f8098f85ac41c240de6 } } ]

But what I'd like:

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

I could use lodash's pluck but is there a way to do it only with mongodb?

1 Answer 1

2

You can change your $project to also reshape the output to provide the structure you're looking for:

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

Output:

[ { _id: 541c2776149002af52ed3c4a,
    author: 'B author',
    content: '2 Content' },
  { _id: 541c2776149002af52ed3c4b,
    author: 'A author',
    content: '1 Content' } ]
Sign up to request clarification or add additional context in comments.

2 Comments

Works great thanks! Is there a way to do this automatically? W/o specifying fields?
@Vinz243 Nope, you need to individually name each field in the projection because you want them at the top level.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.