Way to MongoDB

1.MongoDB术语/概念:database,collection,document,field,index
SQL术语/概念:database,table,row,column,index

2.
所有存储在集合collection中的数据都是BSON格式
BSON是一种类json的一种二进制形式的存储格式,简称BinaryJSON

3.
1).文档中的键/值对是有序的
2).MongoDB区分类型和大小写
3).数据库名字:应全部小写,最多64字节

4.
db和collection都是延时创建的,在添加document时才真正创建
当第一个文档插入时,集合就会被创建(也就是说,可以不用单独创建集合)

5.常用命令:
1).use DATABASE_NAME
如果数据库不存在,则创建数据库,否则切换到指定数据库
刚创建的数据库并不在数据库的列表中(show dbs),要显示它,需要向新建的数据库中插入一些数据
2).查看所有数据库,可以使用show dbs命令
3).删除数据库
db.dropDatabase()
如:

>use test;
switched to db test
>db.dropDatabase();
{"dropped":"test","ok":1}
>show dbs;
admin 0.000GB
local 0.000GB

4).删除集合
db.COLLECTION_NAME.drop()
5).使用insert()或save()方法向集合中插入文档,语法如下:
db.COLLECTION_NAME.insert(document)

>show dbs;
admin 0.000GB
local 0.000GB
>use test;
switched to db test
>db.col.insert({name:"lxw",age:26,tags:["Linux","Python","Network"]})
WriteResult({"nInserted":1})
>show collections
col

以上实例中col是集合名,如果该集合不在该数据库test中,MongoDB会自动创建该集合并插入文档。
查看已插入的文档

>db.col.find()
{"_id":ObjectId("585b79a4f1f502dcb0967539"),"name":"lxw","age":26,"tags":["Linux","Python","Network"]}

插入文档也可以使用db.col.save(document)命令。如果不指定_id字段save()方法类似于insert()方法。如果指定_id字段,则会更新该_id的数据
6).查询数据
db.COLLECTION_NAME.find()
find()方法以非结构化的方式来显示所有文档,如果需要以易读的方式来读取数据,可以使用pretty()方法,语法格式如下:
db.COLLECTION_NAME.find().pretty()
除了find()方法之外,还有一个findOne()方法,它只返回一个文档
7). 只查询某个指定的字段

> db.mof.find({},{news_time:1, _id:0})
{ "news_time" : "2017-01-09" }
{ "news_time" : "2017-01-09" }
{ "news_time" : "2017-01-06" }
{ "news_time" : "2017-01-06" }
{ "news_time" : "2017-01-04" }
{ "news_time" : "2017-01-04" }
{ "news_time" : "2016-12-29" }
{ "news_time" : "2016-12-29" }
{ "news_time" : "2016-12-30" }
{ "news_time" : "2016-12-30" }
{ "news_time" : "2016-12-27" }
{ "news_time" : "2016-12-29" }
{ "news_time" : "2016-12-29" }
{ "news_time" : "2016-12-29" }
{ "news_time" : "2016-12-27" }
{ "news_time" : "2016-12-27" }
{ "news_time" : "2016-12-23" }
{ "news_time" : "2016-12-23" }
{ "news_time" : "2016-12-23" }
{ "news_time" : "2016-12-21" }
Type "it" for more

8). 查看某个collection中的document条数:db.COLLECTION_NAME.find().size() 

References:

MongoDB 教程

原文地址:https://www.cnblogs.com/lxw0109/p/way_to_mongodb.html