提问者:小点点

Mongoose查询按特定字段对主文档和子文档进行排序


我有三份文件。

 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和; 标记。秩序。

TagType将被认为是主文档,因此首先TagType应该按order字段列出,然后TagType将是子文档,它应该按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年前的问题有关:。 但这个问题并不需要答案。 所以我发了新的。

任何帮助都将不胜感激。 谢谢


共1个答案

匿名用户

目前不能直接在数组对象中进行排序,

您可以执行两个选项中的任何一个,

  • 展开数组=>>; 排序=>; 再次将其分组到数组
  • 如果要从查找中获取数据,则使用带有管道的查找它将允许在匹配文档中使用$sort管道

这里您使用的是$lookup,而不是简单的查找,您可以使用“$lookup with pipeline”。

  {
    $lookup: {
      from: "tags",
      as: "tags",
      let: { id: "$_id" },
      pipeline: [
        {
          $match: {
            $expr: { $eq: ["$$id", "$tag_type"] }
          }
        },
        {
          $sort: { order: -1 }
        }
      ]
    }
  },

操场