File write operations in mongo script?

后端 未结 6 1585
执念已碎
执念已碎 2020-12-07 22:22

Is this possible to write the query result to the file from mongo js script. I have searched a lot, but I didn\'t find any solution.

ex:-

cursor = db         


        
6条回答
  •  猫巷女王i
    2020-12-07 23:07

    Whenever I need to write the result of a mongo query to a local file I generally use the the writeFile(pathToFile, stringContents) function.

    Example: let's say that you quickly need to find the email of all registered users and send it to your buddy Jim in the marketing department.

    $ mongo mongodb://my-fancy-mongo-server --ssl -u fancy_username -p fancy_password 
    successfully connected to my-fancy-mongo-server!
    > emails = db.users.distinct('email_address')
    > writeFile("jims_email_list.json", tojson(emails))
    

    or if Jim expect's a CSV file then

    $ mongo mongodb://my-fancy-mongo-server --ssl -u fancy_username -p fancy_password 
    successfully connected to my-fancy-mongo-server!
    > emails = db.users.distinct('email_address')
    > writeFile("jims_email_list.csv", emails.join("\n"))
    

    You can now send Jim the list of emails and save the day!

    To important things to notice about the writeFile function:

    1. The second argument must be a string.
    2. The first argument must be a file that doesn't already exist, otherwise you will get an error.

提交回复
热议问题