3

我有一个非常简单的 mongodb 数据库,其中包含一个名为“test”的集合,我需要向集合中插入 133.306 条记录。这些记录存储在 JSON 文件中。这个文件的大小是 21Mb。50.000 条记录在一秒钟内成功插入。70.000 条记录插入挂起脚本。

编码:

var path = require('path'),
    fs = require('fs'),
    mongodb = require('mongodb'),
    safe = { safe : true },
    rowset;

rowset = JSON.parse(fs.readFileSync(path.join(__dirname, 'test.js')));
console.log('Total records: ' + rowset.length);
rowset = rowset.slice(0, 50000); // OK
// rowset = rowset.slice(0, 70000); // FAIL
console.log('Inserting ' + rowset.length + ' records');

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

        client.createCollection('test', safe, function (err, collection) {
            if (err) throw err;

            collection.insert(rowset, safe, function (err) {
                if (err) throw err;

                client.close(function (err) {
                    if (err) throw err;

                    console.log('done');
                });
            });
        });
    });

mongod 输出的最后几行:

Wed Dec 26 16:50:46 [initandlisten] connection accepted from 127.0.0.1:52003 #854 (4 connections now open)
Wed Dec 26 16:50:46 [initandlisten] connection accepted from 127.0.0.1:52004 #855 (5 connections now open)
Wed Dec 26 16:50:46 [initandlisten] connection accepted from 127.0.0.1:52005 #856 (6 connections now open)

这是行集中的典型记录:

{ _id: 133306,
  product: 23089,
  version: '1.0.0',
  update: null,
  edition: null,
  lang: null,
  entries: [ 54344, 54345 ] }

也许脚本达到了某些阈值或限制?

4

1 回答 1

3

我在我的电脑上用你所说的类型的 150000 个条目测试了你的脚本,它就像一个魅力。对于 20MB 的 json 文件,该过程需要额外的 140MB RAM。

您可以使用以下命令从 mongodb 监控打开的连接:

db.$cmd.sys.inprog.findOne( { $all : true } )

更新:

我试图插入 600000 个条目,但它挂了。你是对的。在这种情况下,您应该使用 mongoimport。我生成了一个包含 1 000 000 个条目的文件,mongo import 在不到一分钟的时间内将它们插入。我需要处理的一些问题:导入文件的格式应如下 BSON(json 超集):

 {"product": 23089,"version": "1.0.0","update": null,"edition": null,"lang": null,"entries": [ 54344, 54345 ]}
 {"product": 23089,"version": "1.0.0","update": null,"edition": null,"lang": null,"entries": [ 54344, 54345 ]}
 {"product": 23089,"version": "1.0.0","update": null,"edition": null,"lang": null,"entries": [ 54344, 54345 ]}
  • 每行一个文档

  • 文档之间没有逗号分隔符

  • 您不应该将它们包含在数组中 []

这是我用于导入的命令:

c:\mongodb\bin>
mongoimport --collection browser12 --file E:\Nodejs\StackOverflow.com\Mongodb\veryBigjson.json --dbpath C:\mongodb\data --port 27016 -d browser12 --ignoreBlanks
于 2012-12-26T20:18:59.943 回答