Read a file from a mongo shell

后端 未结 1 536
执笔经年
执笔经年 2020-12-30 09:33

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

I have a file called rockyou with the contents:

123456
12345
123456789
password
iloveyo         


        
相关标签:
1条回答
  • 2020-12-30 10:32

    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()})
    
    0 讨论(0)
提交回复
热议问题