LeungJZ
V2EX  ›  Node.js

mongoose 如何一次性更新大量文档?急。

  •  1
     
  •   LeungJZ · Apr 24, 2018 · 4969 views
    This topic created in 3011 days ago, the information mentioned may be changed or developed.

    在做 node 爬虫。

    目前用的是 BulkWrite :

    const Book = mongoose.model('Book', bookSchema);
    exports.saveAll = (from_en, books) => {
        const bulkWrite = books.map(book => ({
            replaceOne: {
                filter: {
                    from_en,
                    originId: book.originId
                },
                replacement: book,
                upsert: true
            }
        }))
        return Book.bulkWrite(bulkWrite).catch(error => console.error(error))
    }
    

    然后发现,这么处理 11200 条数据耗时 600s:

    catId: 82 from 5040 to 5600. crawl cost: 10.1min, dataTotal: 11200, upsertTotal: 11000, matchTotal: 200
    mongodb is disonnected
    mongodb: 603757.883ms
    ✨  Done in 604.47s.
    

    这个该如何优化?

    下面是部分爬虫逻辑的代码: while 内部的代码

    机子性能:I7 6700HQ / 16G RAM

    Supplement 1  ·  Apr 28, 2018

    2018年04月28日17:36:55 更新

    现在用 eggjs 的定时任务代替 crontab 的 npm run start,同时,更新的逻辑改为先查询已存在,存在则 replace 不存在则 insert。

    但是现在发现, bulkWrite 的时间还是太长了。很容易出现后续的爬虫在更新时发生 connection fail 的错误。

    { MongoError: connection 12 to 127.0.0.1:27017 timed out
        at Function.MongoError.create (/home/website/bookapp-web-test/node_modules/mongodb-core/lib/error.js:29:11)
        at Socket.<anonymous> (/home/website/bookapp-web-test/node_modules/mongodb-core/lib/connection/connection.js:200:20)
        at Object.onceWrapper (events.js:313:30)
        at emitNone (events.js:106:13)
        at Socket.emit (events.js:208:7)
        at Socket._onTimeout (net.js:420:8)
        at ontimeout (timers.js:482:11)
        at tryOnTimeout (timers.js:317:5)
        at Timer.listOnTimeout (timers.js:277:5)
      name: 'MongoError',
      message: 'connection 12 to 127.0.0.1:27017 timed out' }
    

    而且更新的时间也还是达到了 360000ms 之久。

    saving catId: 83, result: total -> 11200 matched ->undefined, upsert ->undefined;cost: 366340ms
    

    求助啊,真的急。

    LeungJZ
        1
    LeungJZ  
    OP
       Apr 24, 2018
    额,必须充钱才能置顶吗?
    4mrqn07k
        2
    4mrqn07k  
       Apr 25, 2018 via iPhone
    LeungJZ
        3
    LeungJZ  
    OP
       Apr 25, 2018
    @yiding
    不顺序执行的话,如何知道执行完成?
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5529 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 49ms · UTC 06:50 · PVG 14:50 · LAX 23:50 · JFK 02:50
    ♥ Do have faith in what you're doing.