Narwhal为CommonJS提供了访问MongoDB数据库的封装器。
示例代码:
varMongoDB=require("mongodb");vardb=newMongoDB.Mongo().getDB("mydb");varcolls=db.getCollectionNames();colls.forEach(function(el){print(el);});varcoll=db.getCollection("testCollection");coll.drop();vardoc={"name":"MongoDB","type":"database","count":1,"info":{x:203,y:102}}coll.insert(doc)myDoc=coll.findOne();print(myDoc);//Now,letsaddlotsoflittledocumentstothecollectionsowecanexplorequeriesandcursorsfor(vari=0;i<100;i++){coll.insert({"i":i});}print(coll.getCount());//Let'sgetallthedocumentsinthecollectionandprintthemoutvarcur=coll.find();while(cur.hasNext()){print(cur.next());}//Nowuseaquerytoget1documentoutvarquery={i:71};cur=coll.find(query);while(cur.hasNext())print(cur.next());//Nowuseaquerytogetalargersetquery={"i":{"$gt":50}};//i.e.findallwherei>50cur=coll.find(query);while(cur.hasNext())print(cur.next());
评论