Bulk mongodb insert in Meteor or Node

后端 未结 3 1756
情话喂你
情话喂你 2020-12-20 03:20

MongoDB supports bulk insert http://docs.mongodb.org/manual/core/bulk-inserts/

I have tried it in Meteor collection:

Orders.insert([
    { \"cust_id\         


        
相关标签:
3条回答
  • 2020-12-20 03:54

    When inserting a lot of data into the DB, e.g., in a forEach loop, you want to make sure that there is no reactive content on your page that depends on it. Otherwise the reactive rerendering is going to slow your client down tremendously. You can easily insert several thousand document into a collection in a fraction of a second when all templates are disabled, while the same operation can take several minutes with your CPU at 100% on both the client as the server if there is relevant reactivity happening.

    You may want to add a condition to any template whose content depend on this data such as:

    Template.myTemplate.items = function() {
      if (Session.get("active")) {
          return Order.find();
      }
    }
    

    Then you can deactivate all reactive rerendering before your forEach loop and reactivate it again afterwards (Session.set("active", false)).

    0 讨论(0)
  • 2020-12-20 04:04

    You could use exec (nodejs docs) to run a mongo script inside of meteor inside of a Meteor.startup on the server.

    Example:

    Meteor.startup(function () {
        var exec = Npm.require('child_process').exec;
        exec('mongo localhost:27017/meteor path-to/my-insert-script.js', function ( ) {
           // done
        });        
    });
    

    Not optimum, but I think it's your best bet for now. You can also use the command line option --eval against Mongo in exec and pass the insert statement as a string to exec. That might look like this:

    Meteor.startup(function () {
        var exec = Npm.require('child_process').exec;
        exec('mongo localhost:27017/meteor --eval \'db.Orders.insert(' + JSON.stringify(arrOfOrders) + ')\'', function ( ) {
           // done
        });        
    });
    
    0 讨论(0)
  • 2020-12-20 04:09

    You could use rawCollection which is node mongodb driver implemetation in Meteor.Collection.

    await Orders.rawCollection().insertMany(arrOfOrders)

    It works on 70M data in my case. (await makes it synced so you should consider to use it or not for your purpose.)

    0 讨论(0)
提交回复
热议问题