简体   繁体   中英

Insert data into mongodb collection

I want to insert data for whole current month ie November every day of this month and every hour of each day and every minute of each hour and every second of each minute. I tried the following code which I tried for one day.

const data = [
    {
      'name': 'Name 10'
    }, {
      'name': 'Name 9'
    }, {
      'name': 'Name 8'
    }, {
      'name': 'Name 7'
    }, {
      'name': 'Name 6'
    }, {
      'name': 'Name 5'
    }, {
      'name': 'Name 4'
    },
    {
      'name': 'Name 3'
    },
    {
      'name': 'Name 2'
    },
    {
      'name': 'Name 1'
    }
];

const HOURS = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24];
const MINUTES = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59];
    for (let i = 0; i < data.length; i++) {
        for (let h = 0; h < HOURS.length; h++) {
            const hour = new Date().setHours(HOURS[h]);
            for (let m = 0; m < MINUTES.length; m++) {
                const n = data[i].name;
                const value =  Math.floor(Math.random() * (10 - 0 + 1)) + 0;
                const timestamp = new Date(hour).setMinutes(MINUTES[m]);
                new MongoCollection({ 'name': n, 'value': value, 'timestamp': timestamp }).save();
            }
        }       
    }

Any help would be appreciated.

Why do you create arrays and use HOURS.length and MINUTES.length ? for (let h = 0; h < 24; h++) and for (let m = 0; m < 60; m++) does the same.

What is the purpose of - 0 and + 0 ?

Inserting the documents one-by-one will let to serious performance issues.

Anyway, I would suggest moment.js library, would be similar to this.

for (let d of data) {
   var startTime = moment().startOf('month');
   var endTime = moment().endOf('month');
   var docs = [];
   while (startTime.isBeforeOrSame(endTime)) {
      docs.push({ 
          name: d.name, 
          value: Math.floor(Math.random() * 11), 
          timestamp: startTime.toDate() 
      });
      startTime.add(1, 'second');
   }
   db.collection.insertMany(docs);
}

Or maybe put array docs even at top level.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM