mongodb操作

基本概念:

数据库

    数据库是一个物理容器集合。每个数据库都有自己的一套文件系统上的文件。一个单一的MongoDB服务器通常有多个数据库。

集合

      集合是一组MongoDB的文档。它相当于一个RDBMS表。收集存在于一个单一的数据库。集合不执行模式。集合内的文档可以有不同的领域。通常情况下,一个集合中的所有文件是相同或相关的目的。 www.yiibai.com

文档

      文档是一组键 - 值对。文件动态模式。动态模式是指,在相同集合中的文档不需要具有相同的字段或结构组的公共字段的集合的文档,可以容纳不同类型的数据。

下面给出的表显示RDBMS术语使用 MongoDB 的关系


基本操作:

启动mongodb服务:

D:\mongodb\bin>mongod --dbpath "D:\mongodb\data"

linux :

./mongod --dbpath "/var/data"


客户端连接:

D:\mongodb\bin>mongo
MongoDB shell version: 2.6.3
connecting to: test

linux:

./mongo

创建数据库

MongoDB use DATABASE_NAME 用于创建数据库。该命令将创建一个新的数据库,如果它不存在,否则将返回现有的数据库。

use mydb
创建的数据库mydb 列表中是不存在的。要显示的数据库,需要把它插入至少一个文件。

> db.movie.insert({"name":"tutorials point"})
WriteResult({ "nInserted" : 1 })

创建集合

> db.createCollection("mycollection")
{ "ok" : 1 }

创建查看

可以检查通过使用创建的集合命令 show collections

> show collections;
movie
mycollection
system.indexes

删除集合

 db.collection.drop() 是用来从数据库中删除一个集合

> db.yiibai.drop()
true
> show collections;
movie
mycol

数据类型

String : 这是最常用的数据类型来存储数据。在MongoDB中的字符串必须是有效的UTF-8。
Integer : 这种类型是用来存储一个数值。整数可以是32位或64位,这取决于您的服务器。 www.yiibai.com
Boolean : 此类型用于存储一个布尔值 (true/ false) 。
Double : 这种类型是用来存储浮点值。
Min/ Max keys : 这种类型被用来对BSON元素的最低和最高值比较。 yiibai.com
Arrays : 使用此类型的数组或列表或多个值存储到一个键。
Timestamp : 时间戳。这可以方便记录时的文件已被修改或添加。
Object : 此数据类型用于嵌入式的文件。 www.yiibai.com
Null : 这种类型是用来存储一个Null值。
Symbol : 此数据类型用于字符串相同,但它通常是保留给特定符号类型的语言使用。
Date : 此数据类型用于存储当前日期或时间的UNIX时间格式。可以指定自己的日期和时间,日期和年,月,日到创建对象。
Object ID : 此数据类型用于存储文档的ID。
Binary data : 此数据类型用于存储二进制数据。
Code : 此数据类型用于存储到文档中的JavaScript代码。
Regular expression : 此数据类型用于存储正则表达式

插入数据

要插入数据到 MongoDB 集合,需要使用 MongoDB 的  insert() 或 save() 方法。 

> db.mycol.insert({title: 'MongoDB Overview',     description: 'MongoDB is no sq
l database',    by: 'tutorials point',    url: 'http://www.yiibai.com',    tags:
 ['mongodb', 'database', 'NoSQL'],    likes: 100 })

查询

要从MongoDB 查询集合数据,需要使用MongoDB 的 find() 方法

> db.mycol.find()
{ "_id" : ObjectId("53acec47233d13419cd65878"), "title" : "MongoDB Overview", "d
escription" : "MongoDB is no sql database", "by" : "tutorials point", "url" : "h
ttp://www.yiibai.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 10
0 }


结果显示在一个格式化的方式,可以使用 pretty() 方法

> db.mycol.find().pretty()
{
        "_id" : ObjectId("53acec47233d13419cd65878"),
        "title" : "MongoDB Overview",
        "description" : "MongoDB is no sql database",
        "by" : "tutorials point",
        "url" : "http://www.yiibai.com",
        "tags" : [
                "mongodb",
                "database",
                "NoSQL"
        ],
        "likes" : 100
}
{
        "_id" : ObjectId("53aced59233d13419cd65879"),
        "title" : "MongoDB Overview",
        "description" : "MongoDB is no sql database",
        "by" : "tutorials point",
        "url" : "http://www.yiibai.com",
        "tags" : [
                "mongodb",
                "database",
                "NoSQL"
        ],
        "likes" : 120
}

在  find() 方法,如果通过多个键分离',',那么 MongoDB 处理 AND 条件。AND 基本语法如下所示:

db.mycol.find({key1:value1, key2:value2}).pretty() 
> db.mycol.find({"by":"tutorials point","title": "MongoDB Overview"}).pretty()
{
        "_id" : ObjectId("53acec47233d13419cd65878"),
        "title" : "MongoDB Overview",
        "description" : "MongoDB is no sql database",
        "by" : "tutorials point",
        "url" : "http://www.yiibai.com",
        "tags" : [
                "mongodb",
                "database",
                "NoSQL"
        ],
        "likes" : 100
}
{
        "_id" : ObjectId("53aced59233d13419cd65879"),
        "title" : "MongoDB Overview",
        "description" : "MongoDB is no sql database",
        "by" : "tutorials point",
        "url" : "http://www.yiibai.com",
        "tags" : [
                "mongodb",
                "database",
                "NoSQL"
        ],
        "likes" : 120
}

MongoDB Update() 方法

update()方法更新现有文档值。 www.

db.mycol.find({},{"title":1,_id:0})

MongoDB 删除文档

db.mycol.remove({'title':'MongoDB Overview'})


Limit() 方法

db.mycol.find({},{"title":1,_id:0}).limit(2)
<pre code_snippet_id="408802" snippet_file_name="blog_20140627_14_8315141" name="code" class="html">db.mycol.find({},{"title":1,_id:0}).skip(2).limit(2) //跳过2个 可以做分页

 

Sort() 方法

db.COLLECTION_NAME.find().sort({KEY:1}) 

ensureIndex() 方法

索引支持的解析度的查询效率。如果没有索引,MongoDB必须扫描每一个文档的集合,要选择那些文档相匹配的查询语句。这种扫描的效率非常低,会要求 mongod 做大数据量的处理。

索引是一种特殊的数据结构,存储设置在一个易于遍历形式的数据的一小部分。索引存储一个特定的字段或一组字段的值,在索引中指定的值的字段排列的。

aggregate() 方法

聚合操作过程中的数据记录和计算结果返回。聚合操作分组值从多个文档,并可以执行各种操作,分组数据返回单个结果。在SQL COUNT(*)和group by 相当于MongoDB的聚集

db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$sum : 1}}}])
{
   "result" : [
      {
         "_id" : "yiibai point",
         "num_tutorial" : 2
      },
      {
         "_id" : "yiibai point",
         "num_tutorial" : 1
      }
   ],
   "ok" : 1
}


$project:包含、排除、重命名和显示字段


$match:查询,需要同find()一样的参数

$limit:限制结果数量

$skip:忽略结果的数量

$sort:按照给定的字段排序结果

$group:按照给定表达式组合结果

$unwind:分割嵌入数组到自己顶层文件


$sum   总结从集合中的所有文件所定义的值. 

 >  db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$sum : "$likes"}}}])
{ "_id" : null, "num_tutorial" : NumberLong(700) }

$avg   从所有文档集合中所有给定值计算的平均.

> db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$avg : "$likes"}}}])
{ "_id" : null, "num_tutorial" : 100 }

$min    获取集合中的所有文件中的相应值最小.

> db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$min : "$likes"}}}])
{ "_id" : null, "num_tutorial" : NumberLong(100) }

$max  获取集合中的所有文件中的相应值的最大.

> db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$max : "$likes"}}}])
{ "_id" : null, "num_tutorial" : NumberLong(100) }

$push  值插入到一个数组生成文档中.
> db.mycol.aggregate([{$group : {_id : "$by_user", url : {$push: "$url"}}}])
{ "_id" : null, "url" : [ "aaa", "aaa", "aaa", "aaa", "aaa", "aaa", "aaa" ] }

$addToSet  值插入到一个数组中所得到的文档,但不会创建重复

> db.mycol.aggregate([{$group : {_id : "$by_user", url : {$addToSet : "$url"}}}])
{ "_id" : null, "url" : [ "aaa" ] }

$first  根据分组从源文档中获取的第一个文档。通常情况下,这才有意义,连同以前的一些应用 “$sort”-stage.

> db.mycol.aggregate([{$group : {_id : "$by_user", first_url : {$first : "$url"}}}]) 
{ "_id" : null, "first_url" : "aaa" }

$last  根据分组从源文档中获取最后的文档。通常,这才有意义,连同以前的一些应用 “$sort”-stage.

> db.mycol.aggregate([{$group : {_id : "$by_user", last_url : {$last : "$url"}}}])
{ "_id" : null, "last_url" : null }

用户登录./mongo 127.0.0.1:27017/mydb -u root -p

php mongo

模糊查询

$m = new MongoClient();
	$db = $m->mydb;	
	print($_GET['name']);
	$collection = $db->createCollection("mycol");
	$search= array("status"=>true);
	$q   = new MongoRegex("/".$_GET['name']."/");  //模糊查询
	if(!empty($_GET['name'])){
		$search["name"]=$q ;
	}
	$cursor = $collection->find($search)->sort(array("_id"=>-1))->limit(8);


参考文献

MongoDB的聚合函数 Aggregate

http://blog.csdn.net/xtqve/article/details/8983868

mongodb介绍

http://www.yiibai.com/mongodb/mongodb_overview.html 

php mongodb文档

http://www.php.net/manual/zh/book.mongo.php

mapreduce

http://jackyrong.iteye.com/blog/1408548


http://docs.mongodb.org/manual/core/read-operations-introduction/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值