首页 > 解决方案 > mongodb聚合将函数应用于字段

问题描述

作为聚合的一部分,我需要运行此转换:

  let inheritances = await db.collection('inheritance').aggregate([ 
    { $match: { status: 1 }}, // inheritance active
    { $project: { "_id":1, "name": 1, "time_trigger": 1, "signers": 1, "tree": 1, "creatorId": 1, "redeem": 1, "p2sh": 1 } },
    { $lookup:
      {
        from: "user",
        let: { creatorId: { $concat: [ "secretkey", { $toString: "$creatorId" } ] }, time_trigger: "$time_trigger"},
        pipeline: [
          { $match:
            { $expr:  
              { $and:
                [
                  { $eq: [ "$_id", sha256( { $toString: "$$creatorId" } ) ] },
                  { $gt: [ new Date(), { $add: [ { $multiply: [ "$$time_trigger", 24*60*60*1000 ] }, "$last_access" ] } ] }, 
                ]
              }
            }
          },
        ],
        as: "user"
      }, 
    },
    { $unwind: "$user" }
  ]).toArray() 

creatorId 来自查找,为了将其与 _id 进行比较,我首先需要执行 sha256。

我该怎么做?

谢谢。

标签: mongodbaggregate

解决方案


外部函数不适用于聚合框架。默认情况下,所有内容都解析为 BSON。它基本上都是从 BSON 运算符处理到本机 C++ 代码实现,这是为了性能而设计的。

简而言之,你不能这样做。我建议仅将每个文档上的散列值存储为一个新字段,否则您必须在管道之前的代码中执行此操作。


推荐阅读