57-1、2、3NoSQL基础及MongoDB、Mongo-创新互联

02MongoDB基本应用

创新互联是一家业务范围包括IDC托管业务,虚拟空间、主机租用、主机托管,四川、重庆、广东电信服务器租用,托管服务器,成都网通服务器托管,成都服务器租用,业务范围遍及中国大陆、港澳台以及欧美等多个国家及地区的互联网数据服务公司。

配置环境:

node1:192.168.1.121CentOS release 6.7

[root@node1 ~]# cd mongodb-2.6.4/

[root@node1 mongodb-2.6.4]# ls

mongodb-org-2.6.4-1.x86_64.rpm     mongodb-org-shell-2.6.4-1.x86_64.rpm

mongodb-org-mongos-2.6.4-1.x86_64.rpm  mongodb-org-tools-2.6.4-1.x86_64.rpm

mongodb-org-server-2.6.4-1.x86_64.rpm

[root@node1 mongodb-2.6.4]# yum install mongodb-org-server-2.6.4-1.x86_64.rpm mongodb-org-shell-2.6.4-1.x86_64.rpm mongodb-org-tools-2.6.4-1.x86_64.rpm -y

[root@node1 mongodb-2.6.4]# cd

[root@node1 ~]# mkdir -p /mongodb/data

[root@node1 ~]# id mongod

uid=496(mongod) gid=492(mongod) groups=492(mongod)

[root@node1 ~]# chown -R mongod.mongod /mongodb/

[root@node1 ~]# vim /etc/mongod.conf

修改

dbpath=/var/lib/mongo

dbpath=/mongodb/data

修改

bind_ip=127.0.0.1

#bind_ip=127.0.0.1

修改

#httpinterface=true

httpinterface=true

rest=true

[root@node1 ~]# service mongod start

[root@node1 ~]# ls /mongodb/data/

journal  local.0  local.ns  mongod.lock  _tmp

[root@node1 ~]# du -sh /mongodb/data/

3.1G   /mongodb/data/

[root@node1 ~]# ss -tnl

State    Recv-Q Send-Q     Local Address:Port      Peer Address:Port

LISTEN   0    128            :::39591          :::*

LISTEN   0    128            *:27017           *:*

LISTEN   0    128            :::111           :::*

LISTEN   0    128            *:111            *:*

LISTEN   0    128            *:28017           *:*

LISTEN   0    128            *:46453           *:*

LISTEN   0    128            :::22            :::*

LISTEN   0    128            *:22            *:*

LISTEN   0    128        127.0.0.1:631            *:*

LISTEN   0    128           ::1:631           :::*

LISTEN   0    100           ::1:25            :::*

LISTEN   0    100        127.0.0.1:25            *:*

[root@node1 ~]# mongo --host 192.168.1.121

MongoDB shell version: 2.6.4

connecting to: 192.168.1.121:27017/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

> show dbs

admin  (empty)

local  0.078GB

> use testdb

switched to db testdb

> show dbs

admin  (empty)

local  0.078GB

> db.stats()

{

    "db" : "testdb",

    "collections" : 0,

    "objects" : 0,

    "avgObjSize" : 0,

    "dataSize" : 0,

    "storageSize" : 0,

    "numExtents" : 0,

    "indexes" : 0,

    "indexSize" : 0,

    "fileSize" : 0,

    "dataFileVersion" : {

    },

    "ok" : 1

}

> db.version()

2.6.4

> db.getCollectionNames()

[ ]

#插入数据

> db.students.insert({name:"tom",age:23})

WriteResult({ "nInserted" : 1 })

> show collections

students

system.indexes

> show dbs

admin  (empty)

local  0.078GB

testdb  0.078GB

> db.students.stats()

{

    "ns" : "testdb.students",

    "count" : 1,

    "size" : 112,

    "avgObjSize" : 112,

    "storageSize" : 8192,

    "numExtents" : 1,

    "nindexes" : 1,

    "lastExtentSize" : 8192,

    "paddingFactor" : 1,

    "systemFlags" : 1,

    "userFlags" : 1,

    "totalIndexSize" : 8176,

    "indexSizes" : {

        "_id_" : 8176

    },

    "ok" : 1

}

> db.getCollectionNames()

[ "students", "system.indexes" ]

> db.students.insert ({name:"jerry",age:40,gender:"M"})

WriteResult({ "nInserted" : 1 })

> db.students.stats()

{

    "ns" : "test.students",

    "count" : 1,

    "size" : 112,

    "avgObjSize" : 112,

    "storageSize" : 8192,

    "numExtents" : 1,

    "nindexes" : 1,

    "lastExtentSize" : 8192,

    "paddingFactor" : 1,

    "systemFlags" : 1,

    "userFlags" : 1,

    "totalIndexSize" : 8176,

    "indexSizes" : {

        "_id_" : 8176

    },

    "ok" : 1

}

#帮助:

> db.mycoll.help()

> db.mycoll.find.help()

> db.students.find()

{ "_id" : ObjectId("58720933110b5df571418845"), "name" : "jerry", "age" : 40, "gender" : "M" }

{ "_id" : ObjectId("58720a26110b5df571418846"), "name" : "tom", "age" : 23 }

> db.students.count()

2

> db.students.insert({name:"Ou Yangfeng",Age:90,Course:"HaMogong"})

WriteResult({ "nInserted" : 1 })

> db.students.insert({name:"Yang Guo",Age:20,Course:"Meinv Quan"})

WriteResult({ "nInserted" : 1 })

> db.students.insert({name:"Guo Jing",Age:40,Course:"Xiangchong Shibazhang"})

WriteResult({ "nInserted" : 1 })

#查询年龄大于30的记录

> db.students.find({Age:{$gt: 30}})

{ "_id" : ObjectId("58720b48110b5df571418847"), "name" : "Ou Yangfeng", "Age" : 90, "Course" : "HaMogong" }

{ "_id" : ObjectId("58720ba8110b5df571418849"), "name" : "Guo Jing", "Age" : 40, "Course" : "Xiangchong Shibazhang" }

#查询年龄在20到40之间的记录

> db.students.find({Age:{$in: [20,40]}})

{ "_id" : ObjectId("58720b71110b5df571418848"), "name" : "Yang Guo", "Age" : 20, "Course" : "Meinv Quan" }

{ "_id" : ObjectId("58720ba8110b5df571418849"), "name" : "Guo Jing", "Age" : 40, "Course" : "Xiangchong Shibazhang" }

#查看年龄不在20到40之间的记录

> db.students.find({Age:{$nin: [20,40]}})

{ "_id" : ObjectId("58720933110b5df571418845"), "name" : "jerry", "age" : 40, "gender" : "M" }

{ "_id" : ObjectId("58720a26110b5df571418846"), "name" : "tom", "age" : 23 }

{ "_id" : ObjectId("58720b48110b5df571418847"), "name" : "Ou Yangfeng", "Age" : 90, "Course" : "HaMogong" }

#查看Age或age值不在20到40之间的记录

> db.students.find({$or: [{Age: {$nin: [20,40]}}, {age:{$nin:[20,40]}}]})

{ "_id" : ObjectId("58720933110b5df571418845"), "name" : "jerry", "age" : 40, "gender" : "M" }

{ "_id" : ObjectId("58720a26110b5df571418846"), "name" : "tom", "age" : 23 }

{ "_id" : ObjectId("58720b48110b5df571418847"), "name" : "Ou Yangfeng", "Age" : 90, "Course" : "HaMogong" }

{ "_id" : ObjectId("58720b71110b5df571418848"), "name" : "Yang Guo", "Age" : 20, "Course" : "Meinv Quan" }

{ "_id" : ObjectId("58720ba8110b5df571418849"), "name" : "Guo Jing", "Age" : 40, "Course" : "Xiangchong Shibazhang" }

#查看Age或age值在20到40之间的记录

> db.students.find({$or: [{Age: {$in: [20,40]}}, {age:{$in:[20,40]}}]})

{ "_id" : ObjectId("58720933110b5df571418845"), "name" : "jerry", "age" : 40, "gender" : "M" }

{ "_id" : ObjectId("58720b71110b5df571418848"), "name" : "Yang Guo", "Age" : 20, "Course" : "Meinv Quan" }

{ "_id" : ObjectId("58720ba8110b5df571418849"), "name" : "Guo Jing", "Age" : 40, "Course" : "Xiangchong Shibazhang" }

#查看存在gender字段的记录

> db.students.find({gender: {$exists: true}})

{ "_id" : ObjectId("58720933110b5df571418845"), "name" : "jerry", "age" : 40, "gender" : "M" }

#查看不存在gender字段的记录

> db.students.find({gender: {$exists: false}})

{ "_id" : ObjectId("58720a26110b5df571418846"), "name" : "tom", "age" : 23 }

{ "_id" : ObjectId("58720b48110b5df571418847"), "name" : "Ou Yangfeng", "Age" : 90, "Course" : "HaMogong" }

{ "_id" : ObjectId("58720b71110b5df571418848"), "name" : "Yang Guo", "Age" : 20, "Course" : "Meinv Quan" }

{ "_id" : ObjectId("58720ba8110b5df571418849"), "name" : "Guo Jing", "Age" : 40, "Course" : "Xiangchong Shibazhang" }

#修改"tom"的age为21

> db.students.find()

{ "_id" : ObjectId("58720933110b5df571418845"), "name" : "jerry", "age" : 40, "gender" : "M" }

{ "_id" : ObjectId("58720a26110b5df571418846"), "name" : "tom", "age" : 23 }

{ "_id" : ObjectId("58720b48110b5df571418847"), "name" : "Ou Yangfeng", "Age" : 90, "Course" : "HaMogong" }

{ "_id" : ObjectId("58720b71110b5df571418848"), "name" : "Yang Guo", "Age" : 20, "Course" : "Meinv Quan" }

{ "_id" : ObjectId("58720ba8110b5df571418849"), "name" : "Guo Jing", "Age" : 40, "Course" : "Xiangchong Shibazhang" }

> db.students.update({name:"tom"},{$set: {age: 21}})

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.students.find()

{ "_id" : ObjectId("58720933110b5df571418845"), "name" : "jerry", "age" : 40, "gender" : "M" }

{ "_id" : ObjectId("58720a26110b5df571418846"), "name" : "tom", "age" : 21 }

{ "_id" : ObjectId("58720b48110b5df571418847"), "name" : "Ou Yangfeng", "Age" : 90, "Course" : "HaMogong" }

{ "_id" : ObjectId("58720b71110b5df571418848"), "name" : "Yang Guo", "Age" : 20, "Course" : "Meinv Quan" }

{ "_id" : ObjectId("58720ba8110b5df571418849"), "name" : "Guo Jing", "Age" : 40, "Course" : "Xiangchong Shibazhang" }

#删除age值为21的记录

> db.students.remove({age:21})

WriteResult({ "nRemoved" : 1 })

> db.students.find()

{ "_id" : ObjectId("58720933110b5df571418845"), "name" : "jerry", "age" : 40, "gender" : "M" }

{ "_id" : ObjectId("58720b48110b5df571418847"), "name" : "Ou Yangfeng", "Age" : 90, "Course" : "HaMogong" }

{ "_id" : ObjectId("58720b71110b5df571418848"), "name" : "Yang Guo", "Age" : 20, "Course" : "Meinv Quan" }

{ "_id" : ObjectId("58720ba8110b5df571418849"), "name" : "Guo Jing", "Age" : 40, "Course" : "Xiangchong Shibazhang" }

#统计Age值在20到40之间的记录数

> db.students.find({Age: {$in: [20,40]}}).count()

2

#显示Age值在20到40之间的记录,仅显示满足条件的第一条记录

> db.students.find({Age: {$in: [20,40]}}).limit(1)

{ "_id" : ObjectId("58720b71110b5df571418848"), "name" : "Yang Guo", "Age" : 20, "Course" : "Meinv Quan" }

#显示Age值在20到40之间的记录,第一条记录不显示

> db.students.find({Age: {$in: [20,40]}}).skip(1)

{ "_id" : ObjectId("58720ba8110b5df571418849"), "name" : "Guo Jing", "Age" : 40, "Course" : "Xiangchong Shibazhang" }

#显示Age值大于10的记录,仅显示一条满足条件的记录

> db.students.findOne({Age: {$gt: 10}})

{

    "_id" : ObjectId("58720b48110b5df571418847"),

    "name" : "Ou Yangfeng",

    "Age" : 90,

    "Course" : "HaMogong"

}

#删除students表

> db.students.drop()

true

> show collections;

system.indexes

> db.stats()

{

    "db" : "test",

    "collections" : 2,

    "objects" : 1,

    "avgObjSize" : 48,

    "dataSize" : 48,

    "storageSize" : 16384,

    "numExtents" : 2,

    "indexes" : 0,

    "indexSize" : 0,

    "fileSize" : 67108864,

    "nsSizeMB" : 16,

    "dataFileVersion" : {

        "major" : 4,

        "minor" : 5

    },

    "extentFreeList" : {

        "num" : 2,

        "totalSize" : 139264

    },

    "ok" : 1

}

#删除数据库

> db.dropDatabase()

{ "dropped" : "test", "ok" : 1 }

> show dbs

admin  (empty)

local  0.078GB

testdb  0.078GB

03mongodb索引及复制集

[root@node1 ~]# mongo

MongoDB shell version: 2.6.4

connecting to: test

> use testdb

switched to db testdb

> for (i=1;i<=10000;i++) db.students.insert({name:"student"+i, age:(i%120), address:"#85 Wenhua Road, Zhengzhou, China"})

> db.students.find().count()

10000

> db.students.find()

{ "_id" : ObjectId("5871e94113222f399a5240a3"), "name" : "tom", "age" : 23 }

{ "_id" : ObjectId("587232dba7eb9c0c7bd54561"), "name" : "student1", "age" : 1, "address" : "#85 Wenhua Road, Zhengzhou, China" }

{ "_id" : ObjectId("587232dba7eb9c0c7bd54562"), "name" : "student2", "age" : 2, "address" : "#85 Wenhua Road, Zhengzhou, China" }

{ "_id" : ObjectId("587232dba7eb9c0c7bd54563"), "name" : "student3", "age" : 3, "address" : "#85 Wenhua Road, Zhengzhou, China" }

{ "_id" : ObjectId("587232dba7eb9c0c7bd54564"), "name" : "student4", "age" : 4, "address" : "#85 Wenhua Road, Zhengzhou, China" }

{ "_id" : ObjectId("587232dba7eb9c0c7bd54565"), "name" : "student5", "age" : 5, "address" : "#85 Wenhua Road, Zhengzhou, China" }

{ "_id" : ObjectId("587232dba7eb9c0c7bd54566"), "name" : "student6", "age" : 6, "address" : "#85 Wenhua Road, Zhengzhou, China" }

{ "_id" : ObjectId("587232dba7eb9c0c7bd54567"), "name" : "student7", "age" : 7, "address" : "#85 Wenhua Road, Zhengzhou, China" }

{ "_id" : ObjectId("587232dba7eb9c0c7bd54568"), "name" : "student8", "age" : 8, "address" : "#85 Wenhua Road, Zhengzhou, China" }

{ "_id" : ObjectId("587232dba7eb9c0c7bd54569"), "name" : "student9", "age" : 9, "address" : "#85 Wenhua Road, Zhengzhou, China" }

{ "_id" : ObjectId("587232dba7eb9c0c7bd5456a"), "name" : "student10", "age" : 10, "address" : "#85 Wenhua Road, Zhengzhou, China" }

{ "_id" : ObjectId("587232dba7eb9c0c7bd5456b"), "name" : "student11", "age" : 11, "address" : "#85 Wenhua Road, Zhengzhou, China" }

{ "_id" : ObjectId("587232dba7eb9c0c7bd5456c"), "name" : "student12", "age" : 12, "address" : "#85 Wenhua Road, Zhengzhou, China" }

{ "_id" : ObjectId("587232dba7eb9c0c7bd5456d"), "name" : "student13", "age" : 13, "address" : "#85 Wenhua Road, Zhengzhou, China" }

{ "_id" : ObjectId("587232dba7eb9c0c7bd5456e"), "name" : "student14", "age" : 14, "address" : "#85 Wenhua Road, Zhengzhou, China" }

{ "_id" : ObjectId("587232dba7eb9c0c7bd5456f"), "name" : "student15", "age" : 15, "address" : "#85 Wenhua Road, Zhengzhou, China" }

{ "_id" : ObjectId("587232dba7eb9c0c7bd54570"), "name" : "student16", "age" : 16, "address" : "#85 Wenhua Road, Zhengzhou, China" }

{ "_id" : ObjectId("587232dba7eb9c0c7bd54571"), "name" : "student17", "age" : 17, "address" : "#85 Wenhua Road, Zhengzhou, China" }

{ "_id" : ObjectId("587232dba7eb9c0c7bd54572"), "name" : "student18", "age" : 18, "address" : "#85 Wenhua Road, Zhengzhou, China" }

{ "_id" : ObjectId("587232dba7eb9c0c7bd54573"), "name" : "student19", "age" : 19, "address" : "#85 Wenhua Road, Zhengzhou, China" }

#在name字段上构建一个升序索引

> db.students.ensureIndex({name: 1})

{

    "createdCollectionAutomatically" : false,

    "numIndexesBefore" : 1,

    "numIndexesAfter" : 2,

    "ok" : 1

}

#显示表中索引

> db.students.getIndexes()

[

    {

        "v" : 1,

        "key" : {

            "_id" : 1

        },

        "name" : "_id_",

        "ns" : "testdb.students"

    },

    {

        "v" : 1,

        "key" : {

            "name" : 1

        },

        "name" : "name_1",

        "ns" : "testdb.students"

    }

]

#删除索引

> db.students.dropIndex("name_1")

{ "nIndexesWas" : 2, "ok" : 1 }

> db.students.getIndexes()

[

    {

        "v" : 1,

        "key" : {

            "_id" : 1

        },

        "name" : "_id_",

        "ns" : "testdb.students"

    }

]

#创建唯一索引

> db.students.ensureIndex({name: 1},{unique: true})

{

    "createdCollectionAutomatically" : false,

    "numIndexesBefore" : 1,

    "numIndexesAfter" : 2,

    "ok" : 1

}

> db.students.getIndexes()

[

    {

        "v" : 1,

        "key" : {

            "_id" : 1

        },

        "name" : "_id_",

        "ns" : "testdb.students"

    },

    {

        "v" : 1,

        "unique" : true,

        "key" : {

            "name" : 1

        },

        "name" : "name_1",

        "ns" : "testdb.students"

    }

]

#创建唯一索引后,新增相同字段值会提示错误

> db.students.insert({name: "student20", age: 20,})

WriteResult({

    "nInserted" : 0,

    "writeError" : {

        "code" : 11000,

        "errmsg" : "insertDocument :: caused by :: 11000 E11000 duplicate key error index: testdb.students.$name_1  dup key: { : \"student20\" }"

    }

})

> db.students.find({name: "student5000"})

{ "_id" : ObjectId("587232e4a7eb9c0c7bd558e8"), "name" : "student5000", "age" : 80, "address" : "#85 Wenhua Road, Zhengzhou, China" }

#显示查找语句执行过程

> db.students.find({name: "student5000"}).explain()

{

    "cursor" : "BtreeCursor name_1",

    "isMultiKey" : false,

    "n" : 1,

    "nscannedObjects" : 1,

    "nscanned" : 1,

    "nscannedObjectsAllPlans" : 1,

    "nscannedAllPlans" : 1,

    "scanAndOrder" : false,

    "indexOnly" : false,

    "nYields" : 0,

    "nChunkSkips" : 0,

    "millis" : 0,

    "indexBounds" : {

        "name" : [

            [

                "student5000",

                "student5000"

            ]

        ]

    },

    "server" : "node1:27017",

    "filterSet" : false

}

> db.students.find({name: {$gt: "student5000"}}).explain()

{

    "cursor" : "BtreeCursor name_1",

    "isMultiKey" : false,

    "n" : 5552,

    "nscannedObjects" : 5552,

    "nscanned" : 5552,

    "nscannedObjectsAllPlans" : 5552,

    "nscannedAllPlans" : 5552,

    "scanAndOrder" : false,

    "indexOnly" : false,

    "nYields" : 43,

    "nChunkSkips" : 0,

    "millis" : 13,

    "indexBounds" : {

        "name" : [

            [

                "student5000",

                {

                }

            ]

        ]

    },

    "server" : "node1:27017",

    "filterSet" : false

}

另外有需要云服务器可以了解下创新互联cdcxhl.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


网站名称:57-1、2、3NoSQL基础及MongoDB、Mongo-创新互联
分享地址:http://pwwzsj.com/article/dpiiog.html