从mongo shell读取文件

Dyl*_*lan 8 database mongodb nosql

我有一个名为wordlists的数据库和一个名为rockyou的集合.

我有一个名为rockyou的文件,内容如下:

123456
12345
123456789
password
iloveyou
princess
1234567
rockyou
12345678
abc123
Run Code Online (Sandbox Code Playgroud)

我想要做的是将文件中的所有内容加载到我的单词列表数据库中的集合中.我试过搜索谷歌,但mongo的资源似乎很渺茫.我真的可以使用这方面的一些帮助,也可能是这个新的数据库应用程序的一些很好的资源.

谢谢!

**编辑*以下是我使用过的命令以及我尝试过的一些命令.

use wordlists
db.createCollection("rockyou")
db.rockyou.insert(copyFile(~/wordlists/rockyou))
Run Code Online (Sandbox Code Playgroud)

我已经尝试了一些其他方法来插入,但现在意识到还有比这更进一步...

Sal*_*ali 26

如果你真的只想使用mongoshell,你可以使用cat()命令并执行以下操作(txt不是必需的,它只是我的文件命名方式):

use wordlists
var file = cat('path/to/yourFile.txt');  // read the file
var words = file.split('\n'); // create an array of words
for (var i = 0, l = words.length; i < l; i++){ // for every word insert it in the collection
    db.rockyou.insert({'word': words[i]}); 
}
Run Code Online (Sandbox Code Playgroud)

这是在Mongo 3.0.1上测试的,产生了类似的东西:

{ "_id" : ObjectId("551491ee909f1a779b467cca"), "word" : "123456" }
{ "_id" : ObjectId("551491ee909f1a779b467ccb"), "word" : "12345" }
...
{ "_id" : ObjectId("551491ee909f1a779b467cd3"), "word" : "abc123" }
Run Code Online (Sandbox Code Playgroud)

但我会在这里应用逻辑(例如使用python):

import pymongo
connection = pymongo.Connection()
collection = connection.wordlists.rockyou

with open('path/to/yourFile.txt') as f:
    for word in f.readlines():
        collection.insert({'word': word.rstrip()})
Run Code Online (Sandbox Code Playgroud)