【问题标题】:mongodb - find previous and next document in aggregation frameworkmongodb - 在聚合框架中查找上一个和下一个文档
【发布时间】:2021-02-01 00:13:09
【问题描述】:

对我的收藏应用长管道后,我可以获得如下内容:

{
    {
        "_id": "main1",
        "title": "First",
        "code": "C1",
        "subDoc": {
            "active": true,
            "sub_id": "main1sub1",
            "order": 1
        }
    },
        {
        "_id": "main2",
        "title": "Second",
        "code": "C2",
        "subDoc": {
            "active": true,
            "sub_id": "main2sub1",
            "order": 1
        }
    },
        {
        "_id": "main3",
        "title": "Third",
        "code": "C3",
        "subDoc": {
            "active": false,
            "sub_id": "main3sub1",
            "order": 1
        }
    }
}

文档的顺序已经正确。现在我必须找到与给定参数对应的文档之前或之后的文档。例如,如果我知道 { "code" : "C2" } 我必须检索上一个文档(带有 "code" : "C1" 的示例文档)。

我只需要得到那个文件,其他的不需要。

我知道如何使用 find() 方法并按顺序应用 sort() 和 limit(),但我想直接在聚合管道中获取文档,添加必要的阶段来执行此操作。

我尝试了一些 $indexOfArray 和 $arrayElemAt 的组合,但我遇到的第一个问题是我没有数组,它只是文档。

第二个问题是我知道的参数有时可能在子文档中,例如{“sub_id”:“main3sub1”},并且我应该始终获取上一个或下一个父文档作为响应(在示例中,管道应返回文档“main2”作为上一个文档)

我将集合插入到 mongoplayground 以便能够快速执行测试:

mongoplayground

有什么想法吗?

【问题讨论】:

  • 使用{$group: {_id:null, data: {$push:"$$ROOT"}}} 将所有文档放入一个数组中。然后你可以使用例如${subtract: [{$indexOfArray: ["$data.code", "C2"]}, 1]}

标签: mongodb mongodb-query aggregation-framework


【解决方案1】:

如果您只想检索上一个文档,请使用以下查询:

第一种方法:

使用 $match,$sort,$limit

db.collection.aggregate([
  {
    $match: {
      code: {
        "$lt": "C2"
      }
    }
  },
  {
    "$sort": {
      code: -1
    }
  },
  {
    $limit: 1
  }
])

MongoDB Playground

第二种方法:

由@Wernfried Domscheit 指定, 转换为数组,然后使用 $arrayElemAt

db.collection.aggregate([
  {
    $group: {
      _id: null,
      data: {
        $push: "$$ROOT"
      }
    }
  },
  {
    $addFields: {
      "index": {
        $subtract: [
          {
            $indexOfArray: [
              "$data.code",
              "C2"
            ]
          },
          1
        ]
      }
    }
  },
  {
    $project: {
      _id: 0,
      data: {
        $arrayElemAt: [
          "$data",
          "$index"
        ]
      }
    }
  },
  {
    $replaceRoot: {
      newRoot: "$data"
    }
  }
])

MongoDB Playground

【讨论】:

    猜你喜欢
    • 2020-07-15
    • 2020-07-23
    • 2020-05-29
    • 1970-01-01
    • 2017-01-18
    • 1970-01-01
    • 2018-12-14
    • 2023-04-10
    • 1970-01-01
    相关资源
    最近更新 更多