MongoDB 初步shell使用笔记

一、数据储存结构

  MongoDB储存数据分为3层结构。

  dbs——collections——documents。

  最底层的是documents,以Json格式储存数据。collections是文件的动态集合,可以理解为存放文件的抽屉。dbs就是数据库了,能理解为多个抽屉组成的书柜。

二、CRUD(creat, read, updata, delete)操作

1.创建

  一般使用db.collection.insert()方法。

  以下这类似的图片都是官网上的,做的很直观。

  

  users是要插入数据的集合,如果没定义会自动创建。能用show collections查看集合。show collections是shell辅助函数,等价于db.getCollectionNames()。

  插入后如果没有自己定义“_id”键则会自动创建。

 

2.读取

  一般使用db.collection.find()方法或db.collection.findOne()。

  

  query criteria是查询条件。

    “$lt”, “$lte”, “$gt”, “$gte” 分别对应<, <=, >, >=。

    OR查询有两种方法,$in,$or。一个键需要与多个值匹配时用前者,对多个键匹配时则用后者。

db.users.find({users_id:{$in:[12345, "joe"]}})

 

db.restaurants.find(
   { $or: [ { "cuisine": "Italian" }, { "address.zipcode": "10075" } ] }
)

 

    还有$not,$and,查询数组等方法

  projection是投影,也就是返回设定的意思。如果设为1便被指定返回,设为0则被剔除不返回。“_id”默认返回。

  cursor modifier 有三种方法,limit(),skip(),sort()。分别是限制,忽略,排序方法。

 

3.更新

  一般用db.collection.update()方法。

  

  update criteria是更新条件。

  update action是更新行为,有$set, $inc, $push, 等等方法。

  update option是更新选项。

 

4.删除

  一般使用db.collection.remove()方法。

  

  如果要删除整个集合,使用drop()方法更快。

 

 

 

 

 

 

 

 

 

 

 

 

 

  

posted @ 2015-05-05 23:03  ChenRJ  阅读(197)  评论(0编辑  收藏  举报