天天看點

mongodb 查詢目前記錄的上一條和下一條

隻需要修改一下

  1. $sort
  2. $facet:currRow:$match
  3. $facet:root:$match
db.getCollection("").aggregate([
  {
    $sort: {
      "publishDate": 1 #設定排序
    },
    
  },
  {
    $group: {
      _id: 1,
      root: {
        $push: "$$ROOT"
      }
    },
    
  },
  {
    $unwind: { #展開并添加行号
      path: "$root",
      includeArrayIndex: "rownum" 
    }
  },
  {
    $replaceRoot: {
      newRoot: {
        $mergeObjects: [#将行号合并進文檔中
          "$root",
          {
            rownum: "$rownum"
          }
        ]
      }
    }
  },
  {
    $facet: {
      currRow: [#擷取到目前文檔行号
        {
          $match: {#篩選資料
            blogCode: "B0004"
          },
          
        },
        {
          $project: {#擷取到行号
            rownum: 1
          }
        }
      ],
      root: [#篩選條件存在的文檔
        {
          $match: {
            blogCode: {
              $exists: true
            }
          }
        },
        
      ]
    }
  },
  {
    $project: {
      currRow: {
        $arrayElemAt: [#由于上面擷取到的是行号集合,這裡取第一個
          "$currRow",
          0
        ]
      },
      root: 1
    }
  },
  {
    $project: {
      rownum: {#計算出前一個行号和後一個行号
        prev: {
          $add: [
            "$currRow.rownum",
            -1
          ]
        },
        next: {
          $add: [
            "$currRow.rownum",
            1
          ]
        }
      },
      root: 1
    }
  },
  {
    $unwind: "$root"
  },
  {
    $facet: {
      prev: [#根據前一個行号擷取到前一個文檔
        {
          $match: {
            $expr: {
              $eq: [
                "$root.rownum",
                "$rownum.prev"
              ]
            }
          }
        },
        {
          $replaceRoot: {
            newRoot: "$root"
          }
        }
      ],
      next: [#根據後一個行号擷取到後一個文檔
        {
          $match: {
            $expr: {
              $eq: [
                "$root.rownum",
                "$rownum.next"
              ]
            }
          }
        },
        {
          $replaceRoot: {
            newRoot: "$root"
          }
        }
      ],
      
    }
  },
  {
    $project: {
      prev: {
        $arrayElemAt: [
          "$prev",
          0
        ]
      },
      next: {
        $arrayElemAt: [
          "$next",
          0
        ]
      },
    }
  }
])