MongoDB,Node和Express返回不存在于具有大量数据的单独集合中的所有集合

我已经为这根头发拉了好几周了。

我有一个收藏夹(这是一个精简版):

const SubscriberSchema = new Schema({
  publication: { type: Schema.Types.ObjectId,ref: "publicationcollection" },buyer: { type: Schema.Types.ObjectId,ref: "buyercollection" },postCode: { type: String },modifiedBy: { type: String },modified: { type: Date }
});

我也有一个收藏,其中包含175万个英国邮政编码

const PostcodeSchema = new Schema({
  postcode: { type: String }
});

我想做的是返回订户集合中不存在邮政编码集合中的任何记录。

当我尝试使用Mongoose对Subscriber集合中的> 100条记录进行非常简单的聚合时,我收到了超时或返回> 16MB的错误。

这是我到目前为止尝试过的:

router.get(
  "/badpostcodes/:id",passport.authenticate("jwt",{ session: false }),(req,res) => {
    const errors = {};
    Subscriber.aggregate([
      {
        $match: {
          publication: mongoose.Types.ObjectId(req.params.id),postCode: { "$ne": null,$exists: true }
        }
      },{
        $lookup: {
          'from': 'postcodescollections','localField': 'postCode','foreignField': 'postcode','as': 'founditem'
        }
      },// {
      //   $unwind: '$founditem'
      // },{
        $match: {
          'founditem': { $eq: [] }
        }
      }
    ],function (err,result) {
      if (err) {
        console.log(err);
      } else {
        if (result.length > 0) {
          res.json(result);
        } else {
          res.json("0");
        }
      }
    })
  }
);

放松似乎没有任何作用,但已被注释掉,表明我已尝试使用它。

我也尝试过在查找上使用管道,但这没有用,类似于以下内容(对不起,我没有原始代码尝试,因此仅来自内存)

        $lookup: {
          'from': 'postcodescollections','let': { 'postcode': "$postCode" },'pipeline': [
            {
              '$match': {
                'postcode': { $exists: false }
              }
            },{
              '$unwind': "$postCode"
            }
          ],'as': 'founditem'
        }

预先感谢,希望能保留一些头发!

s1y2f3x4 回答:MongoDB,Node和Express返回不存在于具有大量数据的单独集合中的所有集合

您正在对所有不匹配的邮政编码进行匹配,然后撤消这些邮政编码-每个订阅者将获得175万个文档!我认为$lookup中的语法也不正确。

我认为您可以尝试执行以下操作-对数据进行相应调整:

执行$lookup来查找邮政编码中匹配的邮政编码,然后进行匹配以过滤那些没有任何founditem元素的订户:"founditem.0": {$exists: false}

查看示例:

db.getCollection("subscribers").aggregate(
    [
        // Stage 1
        {
            $match: {
                postCode: { "$ne": null,$exists: true }
            }
        },// Stage 2
        {
            $project: { 
                _id: 1,postCode: 1
            }
        },// Stage 3
        {
            $lookup: {
                      from: "postcodescollections",let: { p: "$postCode" },pipeline: [
                        {
                          $match: {
                              $expr:
                                {
                                    $eq: ["$$p","$postcode"] }
                              }

                        },{ $project: { _id: 1 } }
                      ],as: "founditem"
                    }
        },// Stage 4
        {
            $match: {
                "founditem.0": {$exists: false}
            }
        },]
);
本文链接:https://www.f2er.com/3084918.html

大家都在问