我想将单个文档保存到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 } ]更多推荐
如何将查询结果(单个文档)存储到变量中?
发布评论