如何将查询结果(单个文档)存储到变量中?

编程入门 行业动态 更新时间:2024-10-21 16:23:49
本文介绍了如何将查询结果(单个文档)存储到变量中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想将单个文档保存到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 } ]

更多推荐

如何将查询结果(单个文档)存储到变量中?

本文发布于:2023-10-18 11:04:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1504056.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:查询结果   变量   如何将   文档

发布评论

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

>www.elefans.com

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