MongoDB
 sql >> Database >  >> NoSQL >> MongoDB

Leggi un file da una shell mongo

Se vuoi davvero usare solo mongoshell, puoi usare il comando cat() e procedi come segue (txt non è necessario, è solo come è stato chiamato il mio file):

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

Questo è stato testato su Mongo 3.0.1 e ha prodotto qualcosa come:

{ "_id" : ObjectId("551491ee909f1a779b467cca"), "word" : "123456" }
{ "_id" : ObjectId("551491ee909f1a779b467ccb"), "word" : "12345" }
...
{ "_id" : ObjectId("551491ee909f1a779b467cd3"), "word" : "abc123" }

Ma vorrei introdurre qui una logica applicativa (ad esempio con 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()})