Does inserting multiple documents in a Meteor Collection work the same as pure mongodb?

前端 未结 4 913
终归单人心
终归单人心 2021-02-13 04:52

It seems I can\'t do a multiple insert in Meteor the same way it is described here in the Mongodb documentation...

In my js console :

> Test.insert([{na

相关标签:
4条回答
  • 2021-02-13 05:08

    You should always use bulk insert for these things. Meteor doesn't support this out of the box. You could use the batch insert plugin or access the node Mongodb driver to do it natively:

    var items = [{name:'hello'},{name:'hello again'}],
    
        testCollection = new Mongo.Collection("Test"),
        bulk = testCollection.rawCollection().initializeUnorderedBulkOp();
    
    for (var i = 0, len = items.length; i < len; i++) {
        bulk.insert(  items[i] );
    }
    
    bulk.execute();
    

    Note that this only works on mongoDB 2.6+

    0 讨论(0)
  • 2021-02-13 05:16

    From the Meteor leaderboard example code, it looks like you cannot bulk insert. You can either use a loop or underscore iteration function.

    Using underscore,

    var names = [{name:'hello'},{name:'hello again'}]
    
    _.each(names, function(doc) { 
      Test.insert(doc);
    })
    
    0 讨论(0)
  • 2021-02-13 05:18

    For inserting multiple records in your collection you can use mikowals:batch-insert plugin.

    a simple example it would be :

    var names = [{name:'hello'},{name:'hello again'}];
    yourCollection.batchInsert(names);
    

    What you get here is using only one connection you will be able to insert all data in one go same as mongo bulk insert operation.

    0 讨论(0)
  • 2021-02-13 05:23

    As of Nov 2018, you can just use rawCollection to access the collection returned by Mongo Driver and then insert an array of documents as per the Mongo documentation.

    Example:

    let History = new Mongo.Collection('History');
    
    History.rawCollection().insert([entry1, entry2, entry3]);
    
    0 讨论(0)
提交回复
热议问题