在 mongo shell 中将 Mongo 查询输出打印到文件

编程入门 行业动态 更新时间:2024-10-26 10:27:48
本文介绍了在 mongo shell 中将 Mongo 查询输出打印到文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Mongo 2 天,我有 SQL 背景,所以请耐心等待.与 mysql 一样,在 MySQL 命令行中将查询结果输出到机器上的文件非常方便.我试图了解如何使用 Mongo 做同样的事情,同时在 shell 中

2 days old with Mongo and I have a SQL background so bear with me. As with mysql, it is very convenient to be in the MySQL command line and output the results of a query to a file on the machine. I am trying to understand how I can do the same with Mongo, while being in the shell

通过在 shell 之外并执行以下命令,我可以轻松获得我想要的查询的输出:

I can easily get the output of a query I want by being outside of the shell and executing the following command:

mongo localhost:27017/dbname --eval "printjson(db.collectionName.findOne())" > sample.json

上面的方式没问题,但是需要我退出mongo shell或者打开一个新的终端标签来执行这个命令.如果我能在仍然在 shell 中的情况下简单地执行此操作,那将非常方便.

The above way is fine, but it requires me to exit the mongo shell or open a new terminal tab to execute this command. It would be very convenient if I could simply do this while still being inside the shell.

PS:这个问题是我在 SO

P.S: the Question is an offshoot of a question I posted on SO

推荐答案

AFAIK,没有输出到文件的交互选项,之前有一个与此相关的 SO 问题:将mongodb shell 输出打印到文件

AFAIK, there is no a interactive option for output to file, there is a previous SO question related with this: Printing mongodb shell output to File

但是,如果您使用 tee 命令调用 shell,则可以记录所有 shell 会话:

However, you can log all the shell session if you invoked the shell with tee command:

$ mongo | tee file.txt
MongoDB shell version: 2.4.2
connecting to: test
> printjson({this: 'is a test'})
{ "this" : "is a test" }
> printjson({this: 'is another test'})
{ "this" : "is another test" }
> exit
bye

然后你会得到一个包含这个内容的文件:

Then you'll get a file with this content:

MongoDB shell version: 2.4.2
connecting to: test
> printjson({this: 'is a test'})
{ "this" : "is a test" }
> printjson({this: 'is another test'})
{ "this" : "is another test" }
> exit
bye

要删除所有命令并仅保留 json 输出,您可以使用类似于以下内容的命令:

To remove all the commands and keep only the json output, you can use a command similar to:

tail -n +3 file.txt | egrep -v "^>|^bye" > output.json

然后你会得到:

{ "this" : "is a test" }
{ "this" : "is another test" }

这篇关于在 mongo shell 中将 Mongo 查询输出打印到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-03-27 04:03:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/678977.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中将   文件   mongo   shell   Mongo

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!