猫鼬查询以对主文档进行排序子文档按特定字段
我有3个文档.
const designTypeSchema = new mongoose.Schema ({
name : {
type : String,
trim: true,
required : true,
},
image : {
type : String,
trim: true,
required : true,
},
status: {
type : Boolean,
default: true
}
}
);
const tagTypeSchema = new mongoose.Schema ({
name : {
type : String,
required : true,
},
design_type :
{
type: mongoose.Schema.Types.ObjectId,
ref: 'DesignType',
}
,
order : { //need to apply sorting for this field
type : Number,
trim: true,
},
status: {
type : Boolean,
default: true
} } );
const TagSchema = new mongoose.Schema ({
name : {
type : String,
required : true,
},
tag_type : {
type: mongoose.Schema.Types.ObjectId,
ref: 'TagType',
image : {
type : String,
trim: true,
},
order : { //need to apply sorting for this field
type : Number,
},
status: {
type : Boolean,
default: true
}
},
);
我需要对TagType.order& 2个字段进行排序标记顺序.
I need to apply sort on 2 fields, TagType.order & Tag.order.
TagType将被视为主要文档,因此首先TagType应按顺序字段列出,然后Tag将成为子文档,并且应按Tag.order字段列出.
TagType will be considered as main document , so first TagType should list by order field and then Tag will be subdocument and it should list by Tag.order field.
我在下面的查询中尝试过:
I tried below query :
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
}
})
});
使用上面的查询,我得到的是排序结果,但是它仅对主文档而不对子文档(标签)应用排序.我在查询中缺少想要得到的结果.
Using above query i am getting sorted result But its applying sorting on main document only, not on subdocuments(Tags). What i am missing in query to get desire result.
我的问题与此> 6岁的问题有关:.但是那个问题并没有答案.所以我发布了一个新的.
My question is related to this 6 years old question :. But that question have not desire answer. So i posted new one.
任何帮助将不胜感激.谢谢
Any help will be appreciated. Thanks
当前无法直接在数组对象内部进行排序,
Currently sort is not possible directly inside array objects,
您可以选择两个选项,
- if you are getting data from lookup then use lookup with pipeline it will allow to use
$sort
pipeline within match documents - $unwind the array => $sort it => again $group it into array, Refer SO Answer
这里使用的是 $ lookup
,而不是简单的查找,而是可以使用"$ lookup withpipeline".
here you are using $lookup
, instead of simple lookup you can use "$lookup with pipeline".
{
$lookup: {
from: "tags",
as: "tags",
let: { id: "$_id" },
pipeline: [
{
$match: {
$expr: { $eq: ["$$id", "$tag_type"] }
}
},
{
$sort: { order: -1 }
}
]
}
},
第二种可能的解决方案:游乐场
Second possible solution: Playground