上一篇简答描述了一下的MongoDB的介绍,这一篇要进入主题了,来记录MangoDB的用法
> db.foo.save({"name":"xiaoming"}) > db.foo.find() { "_id" : ObjectId("51e50e633c10628f02cfb779"), "name" : "xiaoming" }
> db.foo.save({'name':'xiaoming',age:10,score:90}) > db.foo.save({'name':'xiaozhang',age:10,score:85}) > db.foo.save({'name':'xiaoli',age:11,score:99}) > db.foo.save({'name':'xiaomeng',age:11,score:100}) > db.foo.find() { "_id" : ObjectId("51e50e633c10628f02cfb779"), "name" : "xiaoming" } { "_id" : ObjectId("51e510133c10628f02cfb77a"), "name" : "xiaoming", "age" : 10, "score" : 90 } { "_id" : ObjectId("51e510243c10628f02cfb77b"), "name" : "xiaozhang", "age" : 10, "score" : 85 } { "_id" : ObjectId("51e510353c10628f02cfb77c"), "name" : "xiaoli", "age" : 11, "score" : 99 } { "_id" : ObjectId("51e510403c10628f02cfb77d"), "name" : "xiaomeng", "age" : 11, "score" : 100 } >
> db.foo.find()
> var cursor=db.foo.find() > while(cursor.hasNext())printjson(cursor.next()) { "_id" : ObjectId("51e50e633c10628f02cfb779"), "name" : "xiaoming" } { "_id" : ObjectId("51e510133c10628f02cfb77a"), "name" : "xiaoming", "age" : 10, "score" : 90 } { "_id" : ObjectId("51e510243c10628f02cfb77b"), "name" : "xiaozhang", "age" : 10, "score" : 85 } { "_id" : ObjectId("51e510353c10628f02cfb77c"), "name" : "xiaoli", "age" : 11, "score" : 99 } { "_id" : ObjectId("51e510403c10628f02cfb77d"), "name" : "xiaomeng", "age" : 11, "score" : 100 } >上面的例子显示了游标风格的迭代输出,hasNext()函数告诉我们是否还有数据,如果有则可以调用next()函数获取数据。
> var cursor=db.foo.find() > while(cursor.hasNext())printjson(cursor.next()) { "_id" : ObjectId("51e50e633c10628f02cfb779"), "name" : "xiaoming" } { "_id" : ObjectId("51e510133c10628f02cfb77a"), "name" : "xiaoming", "age" : 10, "score" : 90 } { "_id" : ObjectId("51e510243c10628f02cfb77b"), "name" : "xiaozhang", "age" : 10, "score" : 85 } { "_id" : ObjectId("51e510353c10628f02cfb77c"), "name" : "xiaoli", "age" : 11, "score" : 99 } { "_id" : ObjectId("51e510403c10628f02cfb77d"), "name" : "xiaomeng", "age" : 11, "score" : 100 } >能达到和while同样的效果
> var cursor=db.foo.find(); > printjson(cursor[1]) { "_id" : ObjectId("51e510133c10628f02cfb77a"), "name" : "xiaoming", "age" : 10, "score" : 90 } >不过要注意的是,使用上面这种方式,要注意占用内存的问题,特别是很大的游标对象,有可能会内存溢出,所以应该用迭代的方式来输出。下面是把游标转换成真实的数组类型:
> var arr=db.foo.find().toArray() > arr[2] { "_id" : ObjectId("51e510243c10628f02cfb77b"), "name" : "xiaozhang", "age" : 10, "score" : 85 }
> db.foo.find({name:'xiaoming'}) { "_id" : ObjectId("51e50e633c10628f02cfb779"), "name" : "xiaoming" } { "_id" : ObjectId("51e510133c10628f02cfb77a"), "name" : "xiaoming", "age" : 10, "score" : 90 } >相当于SQL
SELECT * FROM foo WHERE name='xiaoming'
> db.foo.find({name:'xiaoming'},{name:true}) { "_id" : ObjectId("51e50e633c10628f02cfb779"), "name" : "xiaoming" } { "_id" : ObjectId("51e510133c10628f02cfb77a"), "name" : "xiaoming" }对应SQL语句
SELECT name FROM foo WHERE name='xiaoming'