MongoDB 脚本基础 - 如何 [英] Basics of MongoDB Scripts - How to

查看:15
本文介绍了MongoDB 脚本基础 - 如何的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MongoDB 脚本的基础知识是什么?

What are the basics of MongoDB Scripts?

我认为脚本将以 .js 结尾,我们使用 mongo try.js

I think the script will end with .js, and we run it using mongo try.js

但是如果我把

print(db.foo.find())

try.js 并使用 mongo try.js

它会说

MongoDB shell version: 1.6.1
connecting to: test
DBQuery: test.foo -> undefined

如果我通过键入 mongo 并键入

and if I use the interactive shell by typing mongo and type

> db.foo.find()
{ "_id" : ObjectId("4c7a73428261000000003a7e"), "a" : 1 }
> print(db.foo.find())
DBQuery: test.foo -> undefined

{a : 1} 是我之前使用 db.foo.insert({a:1})

执行 MongoDB 脚本的正确方法是什么,以及如何打印 Ruby irb 或 Python 的 IDLE 等内容?谢谢.(Ruby 的 puts a.inspectpa 通常都可以打印出 a 的整个结构( 中的所有变量名和值一个))

what are the proper ways of doing MongoDB Scripts and how to print things out like a Ruby irb or Python's IDLE? thanks. (Ruby's puts a.inspect or p a can both print out the whole structure of a usually (all the variable names and values in a))

alert(db.foo.find())console.log(db.foo.find()) 也不起作用.

推荐答案

外部脚本文件在 shell 上下文之外执行.

The external script files are executed outside of the shell context.

db.foo.find() 数据库命令只返回一个游标;它自己不打印任何内容.当从 shell 发出命令时,shell 将迭代游标并打印结果.从外部脚本文件运行命令时,不会打印任何内容.

The db.foo.find() database command only returns a cursor; it doesn't print anything by itself. When the command is issued from the shell, the shell will iterate the cursor and print the results. When the command is run from an external script file, nothing is printed.

print() 命令将打印出对象的字符串表示形式.在你的情况下,它是光标:

The print() command will print out the string representation of the object. In your case, it's the cursor:

> print(db.foo.find())
DBQuery: test.foo -> undefined

如果您需要打印查询结果,则必须在脚本文件中迭代光标并打印每个结果,类似于 shell 所做的:

If you need to print results of the query, you'll have to iterate the cursor in your script file and print each result, similarly to what the shell does:

function printResult (r) {
  print(tojson(r))
}

db.foo.find().forEach(printResult)

这篇关于MongoDB 脚本基础 - 如何的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆