如何sorting,select和查询mongoose中的子文档

所以我想sorting子文档,但也select和一切。 看来我不能用普通的查询,所以我尝试瓦特/ 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); }); }) }); 

这几乎工作:

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

但是我想要什么:

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

我可以使用lodash的pluck,但有一种方法只能用MongoDB来做到这一点?

您可以更改您的$project也重塑输出提供您正在寻找的结构:

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

输出:

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