mongo shell 中未设置的变量
variables not set in mongo shell
我正在尝试使用 mongo shell,但我在将值存储在 mongo shell
中时遇到了挑战
当我在文档 users 中找到一个用户时,我将其存储在变量 doc 中
> var doc = db.users.find({"username":"anil"});
当我在 mongo shell 中键入 doc 时,我看到 json 对象
> doc
{ "_id" : ObjectId("57325aaa48d9231b11e5cb81"), "username" : "anil", "email" : "mongodb@gmail.com" }
然而,当我再次输入 doc 时,我什么也没看到。它不见了..我在这里做错了什么?
> doc
>
这可能很简单,但我不明白。有人可以指出我做错了什么吗?
这是因为find
returns a cursor and you can only consume all the value once. Here because you filter your document based on _id
value, in the return cursor you only have one document which is consumed the first time you time. If you need to iterate your result many times, you will need to return an array that contains all the documents from the cursor using toArray
, but in your case what you need is findOne
当您打开 mongo shell 时,它会尝试查找 mongod 服务器并默认连接到测试。当您将 mongo shell 中的某些变量分配给 mongod 中的某些文档时,它实际上是从数据库中获取文档,要再次获得相同的结果,您需要再次连接到数据库(意味着您需要再次键入 var doc = db.users.find({"username":"anil"}); )。与您在 shell 中定义 var doc = 4 并且每次键入 doc 都会 return 4 的情况不同。
如果你想在开始时停止传输并做一些处理那么你需要像
一样在它后面添加null
var doc = db.users.find({"username":"anil"});null;
// 在 doc
上做你的工作
前任
另一种选择是使用 find()
游标的 next()
功能。这会将第一条记录的值赋给变量并且它将持续存在。然后可以对变量进行任何需要的操作。
我正在尝试使用 mongo shell,但我在将值存储在 mongo shell
中时遇到了挑战当我在文档 users 中找到一个用户时,我将其存储在变量 doc 中
> var doc = db.users.find({"username":"anil"});
当我在 mongo shell 中键入 doc 时,我看到 json 对象
> doc
{ "_id" : ObjectId("57325aaa48d9231b11e5cb81"), "username" : "anil", "email" : "mongodb@gmail.com" }
然而,当我再次输入 doc 时,我什么也没看到。它不见了..我在这里做错了什么?
> doc
>
这可能很简单,但我不明白。有人可以指出我做错了什么吗?
这是因为find
returns a cursor and you can only consume all the value once. Here because you filter your document based on _id
value, in the return cursor you only have one document which is consumed the first time you time. If you need to iterate your result many times, you will need to return an array that contains all the documents from the cursor using toArray
, but in your case what you need is findOne
当您打开 mongo shell 时,它会尝试查找 mongod 服务器并默认连接到测试。当您将 mongo shell 中的某些变量分配给 mongod 中的某些文档时,它实际上是从数据库中获取文档,要再次获得相同的结果,您需要再次连接到数据库(意味着您需要再次键入 var doc = db.users.find({"username":"anil"}); )。与您在 shell 中定义 var doc = 4 并且每次键入 doc 都会 return 4 的情况不同。
如果你想在开始时停止传输并做一些处理那么你需要像
一样在它后面添加nullvar doc = db.users.find({"username":"anil"});null; // 在 doc
上做你的工作前任
另一种选择是使用 find()
游标的 next()
功能。这会将第一条记录的值赋给变量并且它将持续存在。然后可以对变量进行任何需要的操作。