# MongoDB学习笔记(持续更新)


启动mongo服务

sodo mongo

显示数据库(显示数据库名称和大小,单位GB)

> show dbs
admin   (empty)
local   0.078GB
test    0.078GB
testdb  0.078GB

选择数据库,以test数据库为例

use testdb

创建集合

>db.createCollection('loc')

显示集合

show collections

mongo支持的数据类型(15种,带*的5种的为BSON格式)

String、Integer、Boolean、Double、Min/Max keys(BSON中的最低和最高值对比)、Arrays、Timestamp、Object、Null、Symbol(与Sting相同,用于保存特定符号类型)、Date、ObjectID(用于存储文档的ID)、Binary data(二进制数据)、Regular expression(二进制表达式)、JavaScriptCode*(JS代码)

MongoDB中的文档ID,_id

自动生成,必须字段,可以使用ObjectId(string<16进制字符串>)指定自己的_id值,类型为12字节BSON格式。组成格式如下:

[0][1][2][3] (前4字节为时间戳)
[4][5][6] (3字节机器码)
[7][8] (2字节进程Id)
[9][10][11] (3字节计数器)

mongoDB创建索引

索引将提高查询速度,但会降低插入和删除速度。所有的索引信息都在数据库system.indexes集合中。
查看已有的索引使用:

db.indexes.find()

查看某个集合中创建的索引使用getIndexes命令:

db.collection.getIndexes()

使用地理空间做索引

mongoDB从1.4版本器对地理位置实现了支持。
1、插入含有地理信息数据
定义点数据, 餐馆位置(经纬度[经, 纬]):

db.restaurants.insert({
name: 'StevenZhu',
    loc:{
        type:'Point',  
        coordinates:[52.365895, 39.256781]
    }
})

2、插入街道的地理信息,起点和终点

db.streets.insert({
name: "WestStreet",
loc: {
    type:'LineString',
    coordinates: [[52.36881,4.895632],[52.368756, 4.890021]]
}
})

3、插入区域数据类型,需要保证起点和终点是一致的。

>db.stores.insert({
name: 'SupperMall',
loc: {
    type: 'Polygon',
    coordinates: [[lo1,la2], [lo2,la2], [lo3, la3], [lo1,la1]]
}
})

4、创建地理信息索引:

>db.restaurants.ensureIndex({loc:'2dsphere'})//参数2dsphere将告诉ensureIndex(),它在索引坐标或地球球体上的其他形式的二维信息。默认情况下ensureIndex将假设提供的是经度和纬度,并默认是从-180到180.可以用min和max做覆盖

>db.restaurants.ensureIndex({loc:'2dsphere'},{min:-500,max:500})

5、查询地理信息数据

>db.resaurants.find({loc:[52.5]})