mongodb基础

MongoDB在MAC下的安装

  • 安装

  huijundeMacBook-Pro:~ huijunzhang$ brew install mongodb
  ...
  ==> Downloading https://homebrew.bintray.com/bottles/mongodb-3.2.9.el_capitan.bottle.tar.gz
  ######################################################################## 100.0%
  ==> Pouring mongodb-3.2.9.el_capitan.bottle.tar.gz
  ==> Caveats
  To have launchd start mongodb now and restart at login:
    brew services start mongodb
  Or, if you don't want/need a background service you can just run:
    mongod --config /usr/local/etc/mongod.conf
  ==> Summary
  🍺  /usr/local/Cellar/mongodb/3.2.9: 17 files, 241.2M

 

  • 启动MongoDB

    上面提示的直接启动mongo的方法

mongod --config /usr/local/etc/mongod.conf

 

具体操作如下:

huijundeMacBook-Pro:~ huijunzhang$ mongod --config /usr/local/etc/mongod.conf &
[1] 19869
huijundeMacBook-Pro:~ huijunzhang$ mongo
MongoDB shell version: 3.2.9
connecting to: test
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
    http://docs.mongodb.org/
Questions? Try the support group
    http://groups.google.com/group/mongodb-user
Server has startup warnings: 
2016-08-31T09:30:34.820+0800 I CONTROL  [initandlisten] 
2016-08-31T09:30:34.820+0800 I CONTROL  [initandlisten] ** WARNING: soft rlimits too low. Number of files is 256, should be at least 1000

 

到此,mongoDB在mac下的安装就完成了


一、基本操作

mongodb中的基本操作无非就是增删改查,看下边

insert:

> db.table_name.insert({"name":"zhj","age":20,"province":"henan"})
WriteResult({ "nInserted" : 1 })
> db.table_name.insert({"name":"zjf","age":18,"province":"beijing"})
WriteResult({ "nInserted" : 1 })
> db.table_name.insert({"name":"zg","age":22,"province":"beijing"})
WriteResult({ "nInserted" : 1 })

 

mongo不支持批量插入,如果需要批量插入,就使用for循环操作

find:

> db.table_name.find()
{ "_id" : ObjectId("57c6364278935e710c61131b"), "name" : "zhj", "age" : 20, "province" : "henan" }
{ "_id" : ObjectId("57c6365e78935e710c61131c"), "name" : "zjf", "age" : 18, "province" : "beijing" }
{ "_id" : ObjectId("57c6366e78935e710c61131d"), "name" : "zg", "age" : 22, "province" : "beijing" }

 


  • "无关键字","$ne","$gt","$gte","$lt","$lte"

sql | mongo | 说明 | ---|---|---|

|$gt |大于 =|$gte|大于等于 < |$lt |小于 <=|$lte|小于等于 !=|$ne |不等于 ==| |等于

#select * from table_name where age == 20
db.table_name.find({"age":20})
#select * from table_name where age != 20
db.table_name.find({"age":{$ne:20}})
#select * from table_name where age > 20
db.table_name.find({"age":{$gt:20}})
#select * from table_name where age < 20
db.table_name.find({"age":{$lt:20}})
#select * from table_name where age >= 20
db.table_name.find({"age":{$gte:20}})
#select * from table_name where age <= 20
db.table_name.find({"age":{$lte:20}})

# 具体操作如下
> db.table_name.find({"age":20})
{ "_id" : ObjectId("57c6364278935e710c61131b"), "name" : "zhj", "age" : 20, "province" : "henan" }
> db.table_name.find({"age":{$ne:20}})
{ "_id" : ObjectId("57c6365e78935e710c61131c"), "name" : "zjf", "age" : 18, "province" : "beijing" }
{ "_id" : ObjectId("57c6366e78935e710c61131d"), "name" : "zg", "age" : 22, "province" : "beijing" }
> db.table_name.find({"age":{$gt:20}})
{ "_id" : ObjectId("57c6366e78935e710c61131d"), "name" : "zg", "age" : 22, "province" : "beijing" }
> db.table_name.find({"age":{$lt:20}})
{ "_id" : ObjectId("57c6365e78935e710c61131c"), "name" : "zjf", "age" : 18, "province" : "beijing" }
> db.table_name.find({"age":{$gte:20}})
{ "_id" : ObjectId("57c6364278935e710c61131b"), "name" : "zhj", "age" : 20, "province" : "henan" }
{ "_id" : ObjectId("57c6366e78935e710c61131d"), "name" : "zg", "age" : 22, "province" : "beijing" }
> db.table_name.find({"age":{$lte:20}})
{ "_id" : ObjectId("57c6364278935e710c61131b"), "name" : "zhj", "age" : 20, "province" : "henan" }
{ "_id" : ObjectId("57c6365e78935e710c61131c"), "name" : "zjf", "age" : 18, "province" : "beijing" }

 

  • "无关键字" ,"$or", "$in","$nin"
sqlmongo说明
and    
or $or  
in $in  
not in $nin  
db.table_name.find({"name":"zhj","province":"henan"})
db.table_name.find({$or:[{"province":"henan"},{"province":"beijing"}]})
db.table_name.find({"province":{$in:["henan","beijing"]}})
db.table_name.find({"province":{$nin:["henan","beijing"]}})

# 具体操作如下
> db.table_name.find({"name":"zhj","province":"henan"})
{ "_id" : ObjectId("57c6364278935e710c61131b"), "name" : "zhj", "age" : 20, "province" : "henan" }
> db.table_name.find({$or:[{"province":"henan"},{"province":"beijing"}]})
{ "_id" : ObjectId("57c6364278935e710c61131b"), "name" : "zhj", "age" : 20, "province" : "henan" }
{ "_id" : ObjectId("57c6365e78935e710c61131c"), "name" : "zjf", "age" : 18, "province" : "beijing" }
{ "_id" : ObjectId("57c6366e78935e710c61131d"), "name" : "zg", "age" : 22, "province" : "beijing" }
> db.table_name.find({"province":{$in:["henan","beijing"]}})
{ "_id" : ObjectId("57c6364278935e710c61131b"), "name" : "zhj", "age" : 20, "province" : "henan" }
{ "_id" : ObjectId("57c6365e78935e710c61131c"), "name" : "zjf", "age" : 18, "province" : "beijing" }
{ "_id" : ObjectId("57c6366e78935e710c61131d"), "name" : "zg", "age" : 22, "province" : "beijing" }
> db.table_name.find({"province":{$nin:["henan","beijing"]}})
> 

 

  • 正则表达式

  匹配以'j'开头,'e'结尾的
  db.table_name.find({"name":/^j/,"name":/e$/})

  > db.table_name.find({"name":/^j/,"name":/g$/})
  { "_id" : ObjectId("57c6366e78935e710c61131d"), "name" : "zg", "age" : 22, "province" : "beijing" }

 

  • $where

$where中的value就是我们常用的js

  # find name='zhj'
  db.table_name.find({$where:function(){return this.name == 'zhj'}})

  # 具体操作如下      
  > db.table_name.find({$where:function(){return this.name == 'zhj'}})
  { "_id" : ObjectId("57c6364278935e710c61131b"), "name" : "zhj", "age" : 20, "province" : "henan" }

 

update:

db.table_name.insert({"name":"zhj"},{"name":"zhj","age":18})

 


  • 整体更新:

     var model = db.table_name.findOne({"name":"zhj"})
      model.age = 30
      db.table_name.update({"name":"zhj"},model)
    
      # 具体操作如下
      > var model = db.table_name.findOne({"name":"zhj"})
      > model.age = 30
      30
      > db.table_name.update({"name":"zhj"},model)
      WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
      > db.table_name.find()
      { "_id" : ObjectId("57c6364278935e710c61131b"), "name" : "zhj", "age" : 30, "province" : "henan" }
      { "_id" : ObjectId("57c6365e78935e710c61131c"), "name" : "zjf", "age" : 18, "province" : "beijing" }
      { "_id" : ObjectId("57c6366e78935e710c61131d"), "name" : "zg", "age" : 22, "province" : "beijing" }

     

  • 局部更新:

  ① $inc修改器

$inc也就是increase的缩写,学过sqlserver的同学应该很熟悉,比如我们做一个在线用户状态记录,每次修改会在原有的基础上自增$inc指定的值,如果“文档”中没有此key,则会创建key,下面的例子一看就懂。

# 原数据的age=20,执行完下面语句,age=50,在原来的基础上加了30
db.table_name.update({"name":"zhj"},{$inc:{"age":30}})

# 具体操作如下
> db.table_name.find()
{ "_id" : ObjectId("57c6364278935e710c61131b"), "name" : "zhj", "age" : 30, "province" : "henan" }
{ "_id" : ObjectId("57c6365e78935e710c61131c"), "name" : "zjf", "age" : 18, "province" : "beijing" }
{ "_id" : ObjectId("57c6366e78935e710c61131d"), "name" : "zg", "age" : 22, "province" : "beijing" }
> db.table_name.update({"name":"zhj"},{$inc:{"age":30}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.table_name.find()
{ "_id" : ObjectId("57c6364278935e710c61131b"), "name" : "zhj", "age" : 60, "province" : "henan" }
{ "_id" : ObjectId("57c6365e78935e710c61131c"), "name" : "zjf", "age" : 18, "province" : "beijing" }
{ "_id" : ObjectId("57c6366e78935e710c61131d"), "name" : "zg", "age" : 22, "province" : "beijing" }

  ② $set修改器

db.table_name.update({"name":"zhj"},{$set:{"age":30}})

# 具体操作如下
> db.table_name.update({"name":"zhj"},{$set:{"age":30}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.table_name.find()
{ "_id" : ObjectId("57c6364278935e710c61131b"), "name" : "zhj", "age" : 30, "province" : "henan" }
{ "_id" : ObjectId("57c6365e78935e710c61131c"), "name" : "zjf", "age" : 18, "province" : "beijing" }
{ "_id" : ObjectId("57c6366e78935e710c61131d"), "name" : "zg", "age" : 22, "province" : "beijing" }

 

  • upsert操作

这个可是mongodb创造出来的“词”,大家还记得update方法的第一次参数是“查询条件”吗?,那么这个upsert操作就是说:如果我没有查到,我就在数据库里面新增一条,其实这样也有好处,就是避免了我在数据库里面判断是update还是add操作,使用起来很简单,将update的第三个参数设为true即可。

db.table_name.update({"name":"zhanghj"},{$inc:{"age":30}},true)

# 具体操作如下
> db.table_name.update({"name":"zhanghj"},{$inc:{"age":30}},true)
WriteResult({
    "nMatched" : 0,
    "nUpserted" : 1,
    "nModified" : 0,
    "_id" : ObjectId("57c63ef3a34de94e98acbdd7")
})
> db.table_name.find()
{ "_id" : ObjectId("57c6364278935e710c61131b"), "name" : "zhj", "age" : 30, "province" : "henan" }
{ "_id" : ObjectId("57c6365e78935e710c61131c"), "name" : "zjf", "age" : 18, "province" : "beijing" }
{ "_id" : ObjectId("57c6366e78935e710c61131d"), "name" : "zg", "age" : 22, "province" : "beijing" }
{ "_id" : ObjectId("57c63ef3a34de94e98acbdd7"), "name" : "zhanghj", "age" : 30 }

 

  • 批量更新

在mongodb中如果匹配多条,默认的情况下只更新第一条,那么如果我们有需求必须批量更新,那么在mongodb中实现也是很简单的,在update的第四个参数中设为true即可。例子就不举了。

#有第四个参数的全部更新
> db.table_name.find()
{ "_id" : ObjectId("57c6364278935e710c61131b"), "name" : "zhj", "age" : 30, "province" : "henan" }
{ "_id" : ObjectId("57c6365e78935e710c61131c"), "name" : "zjf", "age" : 18, "province" : "beijing" }
{ "_id" : ObjectId("57c6366e78935e710c61131d"), "name" : "zg", "age" : 22, "province" : "beijing" }
{ "_id" : ObjectId("57c63ef3a34de94e98acbdd7"), "name" : "zhanghj", "age" : 30 }
{ "_id" : ObjectId("57c63fa978935e710c61131e"), "name" : "zhj", "age" : 10, "province" : "hubei" }
{ "_id" : ObjectId("57c63fb678935e710c61131f"), "name" : "zhj", "age" : 10, "province" : "hebei" }
> db.table_name.update({"name":"zhj"},{$set:{"age":2}},false,true)
WriteResult({ "nMatched" : 3, "nUpserted" : 0, "nModified" : 3 })
> db.table_name.find()
{ "_id" : ObjectId("57c6364278935e710c61131b"), "name" : "zhj", "age" : 2, "province" : "henan" }
{ "_id" : ObjectId("57c6365e78935e710c61131c"), "name" : "zjf", "age" : 18, "province" : "beijing" }
{ "_id" : ObjectId("57c6366e78935e710c61131d"), "name" : "zg", "age" : 22, "province" : "beijing" }
{ "_id" : ObjectId("57c63ef3a34de94e98acbdd7"), "name" : "zhanghj", "age" : 30 }
{ "_id" : ObjectId("57c63fa978935e710c61131e"), "name" : "zhj", "age" : 2, "province" : "hubei" }
{ "_id" : ObjectId("57c63fb678935e710c61131f"), "name" : "zhj", "age" : 2, "province" : "hebei" }

#没有第四个参数的只更新第一条
> db.table_name.find()
{ "_id" : ObjectId("57c6364278935e710c61131b"), "name" : "zhj", "age" : 2, "province" : "henan" }
{ "_id" : ObjectId("57c6365e78935e710c61131c"), "name" : "zjf", "age" : 18, "province" : "beijing" }
{ "_id" : ObjectId("57c6366e78935e710c61131d"), "name" : "zg", "age" : 22, "province" : "beijing" }
{ "_id" : ObjectId("57c63ef3a34de94e98acbdd7"), "name" : "zhanghj", "age" : 30 }
{ "_id" : ObjectId("57c63fa978935e710c61131e"), "name" : "zhj", "age" : 2, "province" : "hubei" }
{ "_id" : ObjectId("57c63fb678935e710c61131f"), "name" : "zhj", "age" : 2, "province" : "hebei" }
> db.table_name.update({"name":"zhj"},{$set:{"age":20}},false)
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.table_name.find()
{ "_id" : ObjectId("57c6364278935e710c61131b"), "name" : "zhj", "age" : 20, "province" : "henan" }
{ "_id" : ObjectId("57c6365e78935e710c61131c"), "name" : "zjf", "age" : 18, "province" : "beijing" }
{ "_id" : ObjectId("57c6366e78935e710c61131d"), "name" : "zg", "age" : 22, "province" : "beijing" }
{ "_id" : ObjectId("57c63ef3a34de94e98acbdd7"), "name" : "zhanghj", "age" : 30 }
{ "_id" : ObjectId("57c63fa978935e710c61131e"), "name" : "zhj", "age" : 2, "province" : "hubei" }
{ "_id" : ObjectId("57c63fb678935e710c61131f"), "name" : "zhj", "age" : 2, "province" : "hebei" }
> 

 

remove:

db.table_name.remove()

 

二、高级操作

聚合

常见的聚合操作有:count、distinct、group、mapReduce

count

> db.table_name.find()
{ "_id" : ObjectId("57c6364278935e710c61131b"), "name" : "zhj", "age" : 20, "province" : "henan" }
{ "_id" : ObjectId("57c6365e78935e710c61131c"), "name" : "zjf", "age" : 18, "province" : "beijing" }
{ "_id" : ObjectId("57c6366e78935e710c61131d"), "name" : "zg", "age" : 22, "province" : "beijing" }
{ "_id" : ObjectId("57c63ef3a34de94e98acbdd7"), "name" : "zhanghj", "age" : 30 }
{ "_id" : ObjectId("57c63fa978935e710c61131e"), "name" : "zhj", "age" : 2, "province" : "hubei" }
{ "_id" : ObjectId("57c63fb678935e710c61131f"), "name" : "zhj", "age" : 2, "province" : "hebei" }
> db.table_name.count()
6
> db.table_name.count({"age":2})
2

 

distinct

> db.table_name.distinct("name")
[ "zhj", "zjf", "zg", "zhanghj" ]

 

group

在mongodb里面做group操作有点小复杂,不过大家对sql server 里面的group比较熟悉的话还是一眼能看的明白的,其实group操作本质上形成了一种“k-v”模型,就像C#中的Dictionary,好,有了这种思维,我们来看看如何使用group。

下面举的例子就是按照age进行group操作,value为对应age的姓名。下面对这些参数介绍一下:

  • key: 这个就是分组的key,我们这里是对年龄分组。
  • initial: 每组都分享一个”初始化函数“,特别注意:是每一组,比如这个的age=20的value的list分享一个
  • initial函数,age=22同样也分享一个initial函数。
  • $reduce: 这个函数的第一个参数是当前的文档对象,第二个参数是上一次function操作的累计对象,第一次为initial中的{”perosn“:[]}。有多少个文档, $reduce就会调用多少次。

> db.table_name.find()
{ "_id" : ObjectId("57c6364278935e710c61131b"), "name" : "zhj", "age" : 20, "province" : "henan" }
{ "_id" : ObjectId("57c6365e78935e710c61131c"), "name" : "zjf", "age" : 18, "province" : "beijing" }
{ "_id" : ObjectId("57c6366e78935e710c61131d"), "name" : "zg", "age" : 22, "province" : "beijing" }
{ "_id" : ObjectId("57c63ef3a34de94e98acbdd7"), "name" : "zhanghj", "age" : 30 }
{ "_id" : ObjectId("57c63fa978935e710c61131e"), "name" : "zhj", "age" : 2, "province" : "hubei" }
{ "_id" : ObjectId("57c63fb678935e710c61131f"), "name" : "zhj", "age" : 2, "province" : "hebei" }
> db.table_name.group({
... "key":{"age":true},
... "initial":{"table_name":[]},
... "$reduce":function(cur,prev){
...    prev.table_name.push(cur.name);
... }
... })
[
    {
        "age" : 20,
        "table_name" : [
            "zhj"
        ]
    },
    {
        "age" : 18,
        "table_name" : [
            "zjf"
        ]
    },
    {
        "age" : 22,
        "table_name" : [
            "zg"
        ]
    },
    {
        "age" : 30,
        "table_name" : [
            "zhanghj"
        ]
    },
    {
        "age" : 2,
        "table_name" : [
            "zhj",
            "zhj"
        ]
    }
]

看到上面的结果,是不是有点感觉,我们通过age查看到了相应的name人员,不过有时我们可能有如下的要求:

①:想过滤掉age>25一些人员。

②:有时person数组里面的人员太多,我想加上一个count属性标明一下。

针对上面的需求,在group里面还是很好办到的,因为group有这么两个可选参数: condition 和 finalize。

  • condition: 这个就是过滤条件。
  • finalize:这是个函数,每一组文档执行完后,多会触发此方法,那么在每组集合里面加上count也就是它的活了。

> db.table_name.group({
... "key":{"age":true},
... "initial":{"table_name":[]},
... "$reduce":function(cur,prev){
...    prev.table_name.push(cur.name);
... },
... "finalize":function(out){
... out.count=out.table_name.length;
... },
... "condition":{"age":{$gt:18}}
... })
[
    {
        "age" : 20,
        "table_name" : [
            "zhj"
        ],
        "count" : 1
    },
    {
        "age" : 22,
        "table_name" : [
            "zg"
        ],
        "count" : 1
    },
    {
        "age" : 30,
        "table_name" : [
            "zhanghj"
        ],
        "count" : 1
    }
]

 

mapReduce

参见:http://www.cnblogs.com/huangxincheng/archive/2012/02/21/2361205.html

游标

mongodb里面的游标有点类似我们说的C#里面延迟执行,比如:

  var list=db.person.find();

针对这样的操作,list其实并没有获取到person中的文档,而是申明一个“查询结构”,等我们需要的时候通过for或者next()一次性加载过来,然后让游标逐行读取,当我们枚举完了之后,游标销毁,之后我们在通过list获取时,

发现没有数据返回了。

> var list = db.table_name.find()
> list.forEach(function(x){print(x.name)})
zhj
zjf
zg
zhanghj
zhj
zhj
> list
> 

 

当然我们的“查询构造”还可以搞的复杂点,比如分页,排序都可以加进去。

var single=db.table_name.find().sort({"name":1}).skip(2).limit(2);

 

那么这样的“查询构造”可以在我们需要执行的时候执行,大大提高了不必要的花销。

 

sql:

db.car_db.count({
    "date_create": {
        $gte: ISODate("2016-05-23T16:00:00.000+0000"),
        $lt: ISODate("2016-05-24T16:00:00.000+0000")
    },
    'site': 'che168'
})

聚合:

db.maiche168_car_info.aggregate(
   [
     {
       $group:
         {
               _id: "$shop_id",
            company_name:{ $first: "$company_name"},
            company_address:{ $first: "$company_address"},
            province_name:{ $first: "$province_name"},
            city_name:{ $first: "$city_name"},
            seller_phone:{ $first: "$seller_phone"},
            tags:{ $first: "$tags"},
            total:{ $sum: 1},
         }
     }
   ]
)

---

 

posted @ 2016-08-31 16:12  HuijunZhang  阅读(508)  评论(0编辑  收藏  举报
中国