mongodb不会保存所有数据 [英] mongodb doesn't save all data

查看:333
本文介绍了mongodb不会保存所有数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在mongodb中插入一些矩阵,所以我编写了以下简单代码

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();
  })

当我看到日志时打印出插入的记录太多,例如50,000,但是当我使用mongodb计数记录的数量时,它显示的更少,大约是1,000条记录.

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();

问题出在哪里?

推荐答案

您的异步代码有缺陷,并且db.close()行在异步insert命令全部完成之前执行.您需要控制程序的流向:A)没有发生/排成一百万的并发数据库插入,以及B)等到mongo处理完所有并发数据库后,再关闭连接.如果您不想自己编写代码,请考虑使用诸如async.forEach之类的帮助程序库来提供帮助.

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.

这篇关于mongodb不会保存所有数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆