比较同一集合中 2 个文档的字段以产生差异

问题描述 投票:0回答:1

我有一个系统 我希望生成集合中文档在特定时间戳发生的更改历史记录

假设我们在集合中有一个文档

[
  {
    "property1" : "A",
    "property2" : "B",
    "createdAt" : "2023-05-18T06:36:00.000+00:00"
  }
]

更改为:

[
  {
    "property1" : "A1",
    "property2" : "B",
    "createdAt" : "2023-05-18T07:36:00.000+00:00"
  }
]

然后对于createdAt值

"2023-05-18T07:36:00.000+00:00"
我希望产生像

这样的输出
[
  {
    "propertyChanged" : "property1",
    "oldValue": "A"
    "newValue": "A1"
  }
]

仍在尝试找出最适合此目的的聚合管道运营商

mongodb mongodb-query aggregation-framework
1个回答
0
投票

沿着这些思路怎么样:

  1. 使用

    $match
    根据时间戳过滤文档

    db.collection.aggregate([
      {
        $match: {
          createdAt: "2023-05-18T07:36:00.000+00:00"             }
      },
    
       //2. Use lookup to perform a self-join on the collection to find the previous version of the document based on the createdAt field.
      {
        $lookup: {
          from: "collection",
          let: { createdAt: "$createdAt" },
          pipeline: [
            {
              $match: {
                $expr: {
                  $lt: ["$$createdAt", "$createdAt"]
                }
              }
            },
            { $sort: { createdAt: -1 } },
            { $limit: 1 }
          ],
          as: "previousVersion"
        }
      },
      //3. Use unwind to destructure the arrays from the last operation
      {
        $unwind: "$previousVersion"
      },
    
      //4. Finally you can use project to compare the fields
      {
        $project: {
          propertyChanged: {
            $setDifference: [
              { $objectToArray: "$previousVersion" },
              { $objectToArray: "$$ROOT" }
            ]
          }
        }
      },
      {
        $unwind: "$propertyChanged"
      },
      {
        $project: {
          propertyChanged: "$propertyChanged.k",
          oldValue: {
            $arrayElemAt: ["$previousVersion", "$propertyChanged.k"]
          },
          newValue: {
            $arrayElemAt: ["$$ROOT", "$propertyChanged.k"]
          }
        }
      }
    ]);
    
© www.soinside.com 2019 - 2024. All rights reserved.