定义一个变量
> var len = 10;
For循环 这里的db和data都可以作为对象 save是方法 接收一个临时定义的对象
> for(var i = 0; i < len; i++){db.data.save({x:i})};
WriteResult({ "nInserted" : 1 })
> db.data.find();
{ "_id" : ObjectId("593177646a6bb0f03293efe1"), "x" : 0 }
{ "_id" : ObjectId("593177646a6bb0f03293efe2"), "x" : 1 }
{ "_id" : ObjectId("593177646a6bb0f03293efe3"), "x" : 2 }
{ "_id" : ObjectId("593177646a6bb0f03293efe4"), "x" : 3 }
{ "_id" : ObjectId("593177646a6bb0f03293efe5"), "x" : 4 }
{ "_id" : ObjectId("593177646a6bb0f03293efe6"), "x" : 5 }
{ "_id" : ObjectId("593177646a6bb0f03293efe7"), "x" : 6 }
{ "_id" : ObjectId("593177646a6bb0f03293efe8"), "x" : 7 }
{ "_id" : ObjectId("593177646a6bb0f03293efe9"), "x" : 8 }
{ "_id" : ObjectId("593177646a6bb0f03293efea"), "x" : 9 }
使用游标查询
> var cur = db.data.find();
> cur[1]
{ "_id" : ObjectId("593177646a6bb0f03293efe2"), "x" : 1 }
> printjson(cur[1])
{ "_id" : ObjectId("593177646a6bb0f03293efe2"), "x" : 1 }
> var cur = db.data.find();
对游标执行While循环
> while(cur.hasNext()) printjson(cur.next());
{ "_id" : ObjectId("593177646a6bb0f03293efe1"), "x" : 0 }
{ "_id" : ObjectId("593177646a6bb0f03293efe2"), "x" : 1 }
{ "_id" : ObjectId("593177646a6bb0f03293efe3"), "x" : 2 }
{ "_id" : ObjectId("593177646a6bb0f03293efe4"), "x" : 3 }
{ "_id" : ObjectId("593177646a6bb0f03293efe5"), "x" : 4 }
{ "_id" : ObjectId("593177646a6bb0f03293efe6"), "x" : 5 }
{ "_id" : ObjectId("593177646a6bb0f03293efe7"), "x" : 6 }
{ "_id" : ObjectId("593177646a6bb0f03293efe8"), "x" : 7 }
{ "_id" : ObjectId("593177646a6bb0f03293efe9"), "x" : 8 }
{ "_id" : ObjectId("593177646a6bb0f03293efea"), "x" : 9 }
多么典型的js语法 直接接收一个方法
> db.data.find().forEach(printjson);
{ "_id" : ObjectId("593177646a6bb0f03293efe1"), "x" : 0 }
{ "_id" : ObjectId("593177646a6bb0f03293efe2"), "x" : 1 }
{ "_id" : ObjectId("593177646a6bb0f03293efe3"), "x" : 2 }
{ "_id" : ObjectId("593177646a6bb0f03293efe4"), "x" : 3 }
{ "_id" : ObjectId("593177646a6bb0f03293efe5"), "x" : 4 }
{ "_id" : ObjectId("593177646a6bb0f03293efe6"), "x" : 5 }
{ "_id" : ObjectId("593177646a6bb0f03293efe7"), "x" : 6 }
{ "_id" : ObjectId("593177646a6bb0f03293efe8"), "x" : 7 }
{ "_id" : ObjectId("593177646a6bb0f03293efe9"), "x" : 8 }
{ "_id" : ObjectId("593177646a6bb0f03293efea"), "x" : 9 }
接收一个临时定义的带参数的方法
> db.data.find().forEach(function(e){printjson(e)});
{ "_id" : ObjectId("593177646a6bb0f03293efe1"), "x" : 0 }
{ "_id" : ObjectId("593177646a6bb0f03293efe2"), "x" : 1 }
{ "_id" : ObjectId("593177646a6bb0f03293efe3"), "x" : 2 }
{ "_id" : ObjectId("593177646a6bb0f03293efe4"), "x" : 3 }
{ "_id" : ObjectId("593177646a6bb0f03293efe5"), "x" : 4 }
{ "_id" : ObjectId("593177646a6bb0f03293efe6"), "x" : 5 }
{ "_id" : ObjectId("593177646a6bb0f03293efe7"), "x" : 6 }
{ "_id" : ObjectId("593177646a6bb0f03293efe8"), "x" : 7 }
{ "_id" : ObjectId("593177646a6bb0f03293efe9"), "x" : 8 }
{ "_id" : ObjectId("593177646a6bb0f03293efea"), "x" : 9 }