如何在猫鼬中排序,选择和查询子文档 [英] How to sort, select and query subdocument in mongoose
本文介绍了如何在猫鼬中排序,选择和查询子文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
因此,我正在尝试对子文档进行排序,同时还要对select和所有内容进行排序.似乎我无法进行常规查询,因此尝试了aggregate
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);
});
})
});
这几乎可以工作:
[ { _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这样做吗?
I could use lodash's pluck but is there a way to do it only with mongodb?
推荐答案
您可以更改$project
来重新调整输出的形状,以提供所需的结构:
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) { ...
输出:
[ { _id: 541c2776149002af52ed3c4a,
author: 'B author',
content: '2 Content' },
{ _id: 541c2776149002af52ed3c4b,
author: 'A author',
content: '1 Content' } ]
这篇关于如何在猫鼬中排序,选择和查询子文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文