[SERVER-8519] Javascript for 'For' operator works incorrecly Created: 12/Feb/13  Updated: 19/Mar/13  Resolved: 12/Mar/13

Status: Closed
Project: Core Server
Component/s: JavaScript
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Major - P3
Reporter: Alexander Box Assignee: Stephen Lee
Resolution: Done Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

db version v2.2.2, pdfile version 4.5; Windows 7


Operating System: Windows
Steps To Reproduce:

I'm using the following script:

colls = db.getCollectionNames();
for (x in colls) {
db.dump.insert(

{x : colls[x]}

) ;
};

expected:
>db.dump.find()

{ "_id" : ObjectId("511917a423ebdaf55649e5ba"), "1" : "xxx" } { "_id" : ObjectId("511917a423ebdaf55649e5ba"), "2" : "xxx1" } { "_id" : ObjectId("511917a423ebdaf55649e5ba"), "3" : "xxx2" }

....

{ "_id" : ObjectId("511917a423ebdaf55649e5bb"), "12" : "system.indexes" }

actual:
>db.dump.find()

{ "_id" : ObjectId("511917a423ebdaf55649e5ba"), "x" : "xxx" } { "_id" : ObjectId("511917a423ebdaf55649e5bb"), "x" : "system.indexes" }
Participants:

 Description   

it seems that 'for' works not properly. I've tried 'for in' and usual 'for (x=0;x < 12; x++)' operations. Please see my steps to reproduce.

PS: xxx, xxx1, xxx2 ... system.indexes are collections in my DB

Thank you!



 Comments   
Comment by Stephen Lee [ 08/Mar/13 ]

The mongo shell, which runs Spidermonkey, the Javascript engine, interprets the key of the hash, {{

{x : colls[x]}

}}, as a literal 'x' instead of the value of the variable, x. Instead, try

colls = db.getCollectionNames(); 
for (x in colls) { 
    var obj = {};
    obj[ x ] = colls[x];
    db.dump.insert( obj ) ;
};

and you should see your expected output.

Generated at Thu Feb 08 03:17:39 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.