且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

猫鼬查询以对主文档进行排序子文档按特定字段

更新时间:2023-01-30 13:55:16

当前无法直接在数组对象内部进行排序,

Currently sort is not possible directly inside array objects,

您可以选择两个选项,

  • 如果您要从查找中获取数据,请使用使用管道查找,它将允许在匹配文档中使用 $ sort 管道
  • $ unwind the array =>$ sort ==>再次将其分组到数组中,请参阅答案"
  • 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