【问题标题】:mongodb insert from array fails从数组插入mongodb失败
【发布时间】:2012-12-10 23:23:57
【问题描述】:

我在 ubuntu 服务器上使用 MongoDB。 我想生成我的文档并将它们存储在一个数组中。之后,我想将这些文档插入我的集合中,但不知何故,集合总是空的。重要的是,数据生成与存储分开进行测量。我为此使用了javascript。 但是,这是一些代码:

for (i=0; i<amount; i++)
{                                           
doc = "datetime:" + Math.floor((1262300400+Math.random()%(1356994799-1262300400+1))) + sourceport: " + Math.floor((Math.random()*30000)+2000) ;
myarray[i]=doc;
}

...

for (n=0;n<=myarray.length-1;n++)
    {
        obj_doc = eval('{' + myarray[n] +'}');
        eval('var obj='+myarray[n]);
        obj_doc = '{' + myarray[n] +'}';
        db.mycol.insert(obj_doc);
    }

如果没有 rnd() 函数,它甚至无法工作。 db.mycol.stats() 总是返回“count:0”

【问题讨论】:

    标签: javascript json mongodb insert bson


    【解决方案1】:

    构建要作为对象插入的文档,而不是字符串和eval

    for (i=0; i<amount; i++) {                                           
        doc = {
            datetime: Math.floor((1262300400+Math.random()%(1356994799-1262300400+1))),
            sourceport: Math.floor((Math.random()*30000)+2000)
        };
        myarray[i]=doc;
    }
    
    ...
    
    db.mycol.insert(myarray);
    

    【讨论】:

    • 没有报错,但是集合中还有0个元素
    • @Tyzak 当你运行这个时,amount 的设置是什么?我在 mongo shell 中使用 amount = 50 进行了尝试,它确实插入了 50 个文档。
    • hm 我的金额是 100 ... 字符串是什么?我添加了一个类似 mystring: "test" 的字符串可以吗?
    • @Tyzak 抱歉,我不明白你的问题。
    • hm 抱歉,我用上面的代码和一个额外的项目如 test: "test" 作为字符串尝试过。两者都不起作用-我的收藏统计数据始终为:0 ...我不明白:
    猜你喜欢
    • 1970-01-01
    • 2017-04-23
    • 2016-04-19
    • 2011-02-16
    • 2014-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多