Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read a file from a mongo shell

I have a DB called wordlists and a collection called rockyou.

I have a file called rockyou with the contents:

123456
12345
123456789
password
iloveyou
princess
1234567
rockyou
12345678
abc123

What I would like to do is load all of the contents of the file rockyou into the collection rockyou in my wordlists DB. I have tried searching google but the resources seem slim for mongo. I could really use some help with this and also maybe some good resources for this new to me DB application.

Thanks!

**EDIT* Here are the command I have used and some of what I have tried.

use wordlists
db.createCollection("rockyou")
db.rockyou.insert(copyFile(~/wordlists/rockyou))

I have tried some other methods to insert but now realize there were even further off than this one...

like image 667
Dylan Avatar asked Mar 26 '15 22:03

Dylan


People also ask

How do I access MongoDB from terminal?

To open up the MongoDB shell, run the mongo command from your server prompt. By default, the mongo command opens a shell connected to a locally-installed MongoDB instance running on port 27017 . Try running the mongo command with no additional parameters: mongo.

How do I view databases in Mongo shell?

Listing all the databases in mongoDB console is using the command show dbs . For more information on mongo shell commands, refer the Mongo Shell Quick Reference.


1 Answers

If you really want to use only mongoshell, you can use cat() command and do the following (txt is not necessary, it is just how my file was named):

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

This was tested on Mongo 3.0.1 and produced something like:

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

But I would introduce an application logic here (for example with 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()})
like image 162
Salvador Dali Avatar answered Oct 11 '22 06:10

Salvador Dali