mongodb doesn't save all data

I need to insert some matrix in mongodb,so I wrote simple following code

var MongoClient = require('mongodb').MongoClient;    
var matrisMaker = function(d1,d2){
    var result = new Array();
    for (var i = 0;i < d1;i++){
        result.push(new Array());
        for (var k = 0;k < d2;k++){
            result[i].push(Math.round(Math.random() * 1000000000000));
        }
    }
    return result;
};

  MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
    if(err) throw err;

    var collection = db.collection('matris');

    for (var counter = 0;counter < 10000000;counter++){
        var insertObject = {
                'matrisA':matrisMaker(20,20),
                'matrisB':matrisMaker(20,20),
                'resultA':new Object(),
                'resultB':new Object()
        };
        collection.insert(insertObject, function(err, docs) {
            if (err)
                throw err;
        });
        delete insertObject;
        if ((counter % 1000) == 0)
            console.log(counter);
    }
    db.close();
  })

when I see log it printed that too many records inserted,like 50,000,but when I use mongodb to count amount of records,it display less,something near 1,000 records.

>use test;
>db.matris.count();

where is the problem?

Your asynchronous code is flawed and your db.close() line executes before your asynchronous insert commands have all completed. You need to control the flow of your program to A) not have a million concurrent database inserts happening/queued and B) wait until they have all been processed by mongo before closing the connection. Consider a helper library such as async.forEach to help with this if you don't want to code it yourself.