1. 插入
j = {name:"mongo"};
t = {x:3};
db.things.save(j);
db.things.save(t);
db.things.find();
结果:
{ "_id" : ObjectId("513b3741d003e00702f229bd"), "name" : "mongo" }
{ "_id" : ObjectId("513b3747d003e00702f229be"), "x" : 3 }
2. for循环
for(var i=1;i<10;i++){db.things.save({x:4,j:i});};
db.things.find();
结果:
{ "_id" : ObjectId("513b3741d003e00702f229bd"), "name" : "mongo" }
{ "_id" : ObjectId("513b3747d003e00702f229be"), "x" : 3 }
{ "_id" : ObjectId("513b38d4d003e00702f229bf"), "x" : 4, "j" : 1 }
{ "_id" : ObjectId("513b38d4d003e00702f229c0"), "x" : 4, "j" : 2 }
{ "_id" : ObjectId("513b38d4d003e00702f229c1"), "x" : 4, "j" : 3 }
{ "_id" : ObjectId("513b38d4d003e00702f229c2"), "x" : 4, "j" : 4 }
{ "_id" : ObjectId("513b38d4d003e00702f229c3"), "x" : 4, "j" : 5 }
{ "_id" : ObjectId("513b38d4d003e00702f229c4"), "x" : 4, "j" : 6 }
{ "_id" : ObjectId("513b38d4d003e00702f229c5"), "x" : 4, "j" : 7 }
{ "_id" : ObjectId("513b38d4d003e00702f229c6"), "x" : 4, "j" : 8 }
{ "_id" : ObjectId("513b38d4d003e00702f229c7"), "x" : 4, "j" : 9 }
var cursor = db.things.find();
while(cursor.hasNext()){printjson(cursor.next());}
结果:
{ "_id" : ObjectId("513b3741d003e00702f229bd"), "name" : "mongo" }
{ "_id" : ObjectId("513b3747d003e00702f229be"), "x" : 3 }
{ "_id" : ObjectId("513b38d4d003e00702f229bf"), "x" : 4, "j" : 1 }
{ "_id" : ObjectId("513b38d4d003e00702f229c0"), "x" : 4, "j" : 2 }
{ "_id" : ObjectId("513b38d4d003e00702f229c1"), "x" : 4, "j" : 3 }
{ "_id" : ObjectId("513b38d4d003e00702f229c2"), "x" : 4, "j" : 4 }
{ "_id" : ObjectId("513b38d4d003e00702f229c3"), "x" : 4, "j" : 5 }
{ "_id" : ObjectId("513b38d4d003e00702f229c4"), "x" : 4, "j" : 6 }
{ "_id" : ObjectId("513b38d4d003e00702f229c5"), "x" : 4, "j" : 7 }
{ "_id" : ObjectId("513b38d4d003e00702f229c6"), "x" : 4, "j" : 8 }
{ "_id" : ObjectId("513b38d4d003e00702f229c7"), "x" : 4, "j" : 9 }
数组形式:
var cursor = db.things.find();
printjson(cursor[3]);
循环条件:
db.things.find({x:4},{j:true}).forEach(printjson);
结果:
{ "_id" : ObjectId("513b38d4d003e00702f229bf"), "j" : 1 }
{ "_id" : ObjectId("513b38d4d003e00702f229c0"), "j" : 2 }
{ "_id" : ObjectId("513b38d4d003e00702f229c1"), "j" : 3 }
{ "_id" : ObjectId("513b38d4d003e00702f229c2"), "j" : 4 }
{ "_id" : ObjectId("513b38d4d003e00702f229c3"), "j" : 5 }
{ "_id" : ObjectId("513b38d4d003e00702f229c4"), "j" : 6 }
{ "_id" : ObjectId("513b38d4d003e00702f229c5"), "j" : 7 }
{ "_id" : ObjectId("513b38d4d003e00702f229c6"), "j" : 8 }
{ "_id" : ObjectId("513b38d4d003e00702f229c7"), "j" : 9 }
limit结果集数量
db.things.find().limit(3);
结果:
{ "_id" : ObjectId("513b3741d003e00702f229bd"), "name" : "mongo" }
{ "_id" : ObjectId("513b3747d003e00702f229be"), "x" : 3 }
{ "_id" : ObjectId("513b38d4d003e00702f229bf"), "x" : 4, "j" : 1 }