如何解决猫鼬查询以按特定字段对主文档和子文档进行排序
我有3个文档。
const designTypeSchema = new mongoose.Schema ({
name : {
type : String,trim: true,required : true,},image : {
type : String,status: {
type : Boolean,default: true
}
}
);
const tagTypeSchema = new mongoose.Schema ({
name : {
type : String,design_type :
{
type: mongoose.Schema.Types.ObjectId,ref: 'DesignType',order : { //need to apply sorting for this field
type : Number,default: true
} } );
const TagSchema = new mongoose.Schema ({
name : {
type : String,tag_type : {
type: mongoose.Schema.Types.ObjectId,ref: 'TagType',order : { //need to apply sorting for this field
type : Number,default: true
}
},);
我需要对TagType.order和Tag.order 2个字段进行排序。
TagType将被视为主要文档,因此首先TagType应该按顺序字段列出,然后Tag将成为子文档,并且应该按Tag.order字段列出。
我尝试了以下查询:
TagType.aggregate(
[
{
$lookup: {
from: "tags",localField: "_id",foreignField: "tag_type",as: "tags",{
$lookup: {
from: "designtypes",localField: "design_type",foreignField: "_id",as: "designtype",}
},{
$project:
{
_id: 1,name: 1,tag_type: 1,order: 1,"designtype.name":1,"tags._id":1,"tags.name":1,"tags.image":1,"tags.order":1,totalTags: {$size: "$tags"},{
$sort : {
"order": -1,'tags.order' : -1
}
},]
).exec(function(err,results) {
if (err) {
throw err;
}
res.status(200).json({
message: 'success',total: results.length,response: {
data: results
}
})
});
使用上面的查询,我得到的是排序结果,但是它仅对主文档而不对子文档(标签)应用排序。我在查询中缺少想要的结果。
我的问题与此6 years old question有关:但是那个问题并没有答案。所以我发布了一个新的。
任何帮助将不胜感激。谢谢
解决方法
当前无法直接在数组对象内部进行排序,
您可以选择两个选项,
- 如果您要从查找中获取数据,请使用lookup with pipeline,它将允许在匹配文档中使用
$sort
管道 - $ unwind the array => $ sort it =>再次$ group到数组Refer SO Answer
这里使用的是$lookup
,而不是简单的查找,可以使用“带有管道的$ lookup”。
{
$lookup: {
from: "tags",as: "tags",let: { id: "$_id" },pipeline: [
{
$match: {
$expr: { $eq: ["$$id","$tag_type"] }
}
},{
$sort: { order: -1 }
}
]
}
},
第二种可能的解决方案:Playground
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。