在处理大量数据时,有没有办法让连接速度更快?

时间:2018-06-06 03:57:38

标签: node.js mongodb join

我正在使用mongo和nodejs。

目前我有以下收藏品:

entryMore {
entryId
...
}

filesize {
entryId
...
}

entryIam {
entryId
...
}

entryStatus {
entryId
...
}

entryPubStatus {
entryId
....
}

它们都是entryId的一对一映射

我正在使用以下代码加入nodejs中的所有集合

// db
const { MongoClient } = require('mongodb');
const fs = require('fs');
const Json2csvParser = require('json2csv').Parser;


// run catch err
run()
  .catch(error => console.error(error.stack));


async function run() {
  // connect
  const client = await MongoClient.connect('mongodb://user:pass@127.0.0.1:27017');

  // db
  const db = client.db('kal');

  // The only way to use `$lookup` in MongoDB 3.2 and 3.4
  const docs = await db.collection('entryMore').aggregate([

    // filesize
    {
      $lookup: {
        from: 'filesize',
        localField: 'entryId',
        foreignField: 'entryId',
        as: 'filesize'
      }
    },
    {
      // deconstruct and map to one by one
      $unwind: '$filesize'
    },

    // Iam
    {
      $lookup: {
        from: 'entryIam',
        localField: 'entryId',
        foreignField: 'entryId',
        as: 'entryIam'
      }
    },
    {
      $unwind: '$entryIam'
    },

    // entry status
    {
      $lookup: {
        from: 'entryStatus',
        localField: 'entryId',
        foreignField: 'entryId',
        as: 'entryStatus'
      }
    },
    {
      $unwind: '$entryStatus'
    },

    // pub status
    {
      $lookup: {
        from: 'entryPubStatus',
        localField: 'entryId',
        foreignField: 'entryId',
        as: 'entryPubStatus'
      }
    },
    {
      $unwind: '$entryPubStatus'
    },

     // Final
    {
      $project: {
        _id: 0,
        entryId: 1,
        name: 1,
        //description: 1,
        userId: 1,

        creatorId: 1,
        msDuration: 1,
        categories: 1,
        categoriesIds: 1,

        createdAt: 1,
        updatedAt: 1,
        tags: 1,
        downloadUrl: 1
      }
    }

  ]);

  const json2csvParser = new Json2csvParser({field});
  const csv = json2csvParser.parse(docs);

  await writeFile('./csv/entrySheet.csv', csv);
  console.log('done!');
  process.exit(); 
}   

每个集合都有 97k记录。生成csv需要整个日期。我想知道有没有办法改进它?

1 个答案:

答案 0 :(得分:0)

我同意@NeilLunn所写的内容。但是为了澄清你的问题,$lookup在输入文档中对foreignField执行与localField的相等匹配。如果from集合中的文档不包含foreignField,则$lookup会将该值视为null以进行匹配。
因此,继续在您的外地字段上创建一个索引,这样您就可以进行97k索引命中而不是97k表扫描。它必然会降低时间