如何将查询结果(单个文档)存储到变量中? [英] How to store query result (a single document) into a variable?

查看:74
本文介绍了如何将查询结果(单个文档)存储到变量中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将单个文档保存到Mongo JS shell中的变量中,并为以后的操作操纵该文档(读/写多个属性),但是Mongo JS似乎并没有在变量中放入任何内容:

I would like to save a single document into a variable in Mongo JS shell, and manipulate the document (read/write several attributes) for latter operations, but Mongo JS does not seem to put anything into the variable:

> a = db.col.find().limit(1)
{ "_id" : ObjectId("52dfccba5fd17fe6a4d0051a"), "a" : 16807, "b" : 475249 }
> a
>

mongo支持使用吗?还是有一个错误?

Does mongo support the usage? Or was there a mistake?

推荐答案

您需要像这样使用var:

> var a = db.col.find().limit(1)
{ "_id" : ObjectId("52dfccba5fd17fe6a4d0051a"), "a" : 16807, "b" : 475249 }
> a
{ "_id" : ObjectId("52dfccba5fd17fe6a4d0051a"), "a" : 16807, "b" : 475249 }

进行一些测试,我注意到find()方法似乎确实将变量设置为游标.在这种情况下,您将在下一条语句之后丢失该变量.

Doing some testing I have noticed that the find() method does appear to be setting the variable to a cursor. In these cases, you lose the variable after the next statement.

> var a = db.col.find().limit(1)
{ "_id" : ObjectId("52dfccba5fd17fe6a4d0051a"), "a" : 16807, "b" : 475249 }
> var b = 'test'
> a
>

如果您需要将变量保留更长的时间,请尝试在使用toArray()进行设置之前明确地对变量进行迭代.

If you need to keep the variable around for longer, try explicitly iterating the variable before setting it using toArray().

> var a = db.col.find().limit(1).toArray()
{ "_id" : ObjectId("52dfccba5fd17fe6a4d0051a"), "a" : 16807, "b" : 475249 }
> var b = 'test'
> a
[
  {
    "_id" : ObjectId("52dfccba5fd17fe6a4d0051a"),
    "a" : 16807,
    "b" : 475249
  }
]

这篇关于如何将查询结果(单个文档)存储到变量中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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