2015-10-13 54 views
0

运行查询时,我想将该查询的结果放入另一个文件 我的查询在mongo终端中成功运行。MongoDb:如何将mongoDb查询结果写入文件?

db.questions.find({"question" : {$regex : ".*.*"}},{question :1,_id:0,id:1}); 
{ "id" : 0, "question" : "Amount was debited from my account, but ticket was not 
generated. What should I do now?" } 
{ "id" : 1, "question" : "How safe is goCash?" } 
{ "id" : 2, "question" : "How referral program and goCash works?" } 

现在检查下面的图片: here

通过这一点,我可以在任何类型的文件,只需添加写>> filename.extension

现在主要的问题是与这一个: here

当我使用find而不是findOne a nd使用正则表达式,它显示意想不到的标记

任何人都知道我可以如何修改它以获得所需的结果。

+0

为更好地理解检查此链接:https://mlichtenberg.wordpress.com/2013/11/21/directing-mongodb-query-results-to-a-file/ –

+0

错误是因为语法无效。你正在使用'{“question”:$ regex:“。*。*”}'而不是'{“question”:{$ regex:“。*。*”}}'(缺少大括号)。 – thegreenogre

+0

D:\ mongodb \ mongodb \ bin> mongo localhost/database -eval“printjson(db.questions.find({”question“:{$ regex:”。*。*“}}))”//我用这个如你所建议的,但仍然存在问题。 –

回答

1

您在命令行中使用"(qoutes)。尝试使用{'question' : { \$regex : '.*'}}

此外,db.collection.find()方法返回一个游标。将它重定向到文件只会写入光标json。要访问文档,您需要迭代光标。

mongo localhost/database -eval "var cursor = {'question' : { \$regex : '.*'}}; while(cursor.hasNext()){ printjson(cursor.next())}" 

blog中的所有示例均以json格式返回结果。

您还可以使用任何mongo-drivers将结果写入文件。

+0

单引号为我工作。谢谢但不需要正斜杠。如果还有其他人也跟着这个答案,你需要在你的查询前加上.Final语句看起来像这样。'mongo localhost/database --eval“var x = db.questions.find({'question':{$ regex :'。*。*'}},{question:1,id:1,_id:0}); while(x.hasNext()){printjson(x.next())}“>> out.txt' –