【问题标题】:Is there any way to aggregate two collection within range of specific field's value?有没有办法在特定字段的值范围内聚合两个集合?
【发布时间】:2020-09-30 15:19:44
【问题描述】:

我是 MongoDB 的新手,我想使用 $lookup 函数聚合两个集合。 有什么方法可以将集合 A 中的字段与集合 B 中的字段在 x 范围内进行比较?

例如:

集合 A 的时间(下面代码中名为时间戳的变量)信息是 12:00:00

集合 B 的时间(下面代码中名为时间戳的变量)信息是 12:01:00

我想在 1 秒的范围内聚合文档。

这是我当前的代码示例:

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://ipaddress/tms";

MongoClient.connect(url, function (err, db) {
    if (err) throw err;
    var dbo = db.db("tms");
    dbo.collection('transaction_logs').aggregate([
        {
            $lookup:
                {
                    from: 'transactionLogs',
                    localField: 'deviceSn' && 'deviceName' && 'timestamp',
                    foreignField: 'deviceSn' && 'deviceName' && 'timestamp',
                    as: 'transactionLogs_docs'
                }
        },
        { $out: "integrated_transaction_logs" }
    ]).toArray(function (err, res) {
        if (err) throw err;
        console.log(JSON.stringify(res));
        db.close();
    });
});

【问题讨论】:

    标签: node.js mongodb


    【解决方案1】:

    如果您使用的是 Mongo 3.6+ 版本,则可以使用 "new" $lookup 版本,它允许您使用自定义管道。

    策略是通过减去它们来计算两个日期之间的差异,如果该差异的绝对值小于 1000(以毫秒为单位的秒),那么我们将匹配文档。

    请注意$lookup 是一个非常昂贵的阶段,并且对于collection_one 中的每个文档,它的使用效果不会很好,您必须扫描并计算collection_two 中每个文档的差异.

    我创建了自己的示例集合,因为您没有提供任何示例:

      "collection": [
        {
          id: 1,
          date: ISODate("2020-09-24T02:24:45.631Z"),
          
        },
        {
          id: 2,
          date: ISODate("2020-09-24T04:24:45.632Z"),
          
        }
      ],
      "collection_two": [
        {
          id: 1,
          colTwoDate: ISODate("2020-09-24T02:24:46.431Z"),
          
        },
        {
          id: 2,
          colTwoDate: ISODate("2020-09-24T02:24:44.832Z"),
          
        },
        {
          id: 3,
          colTwoDate: ISODate("2020-09-24T02:30:00.000Z"),
          
        }
      ]
    

    管道:

    db.collection.aggregate([
      {
        "$lookup": {
          "from": "collection_two",
          "let": {
            "colOneDate": "$date"
          },
          "pipeline": [
            {
              $match: {
                $expr: {
                  $lte: [
                    {
                      $abs: {
                        "$subtract": [
                          "$$colOneDate",
                          "$colTwoDate"
                        ]
                      }
                    },
                    1000
                  ]
                }
              }
            }
          ],
          "as": "matched"
        }
      }
    ])
    

    Mongo Playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多