MongoDB
 sql >> Base de Dados >  >> NoSQL >> MongoDB

Ler um arquivo de um shell mongo


Se você realmente deseja usar apenas o mongoshell, pode usar o comando cat() e faça o seguinte (txt não é necessário, é apenas como meu arquivo foi nomeado):
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]}); 
}

Isso foi testado no Mongo 3.0.1 e produziu algo como:
{ "_id" : ObjectId("551491ee909f1a779b467cca"), "word" : "123456" }
{ "_id" : ObjectId("551491ee909f1a779b467ccb"), "word" : "12345" }
...
{ "_id" : ObjectId("551491ee909f1a779b467cd3"), "word" : "abc123" }

Mas eu introduziria uma lógica de aplicativo aqui (por exemplo, com 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()})