MongoDB基础

Posted xingweikun

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MongoDB基础相关的知识,希望对你有一定的参考价值。


书接上文

MongoDB $type 操作符

$type操作符是基于BSON类型来检索集合中匹配的数据类型,并返回结果。

MongoDB 中可以使用的类型如下表所示:

> db.col.insert({
... title:'php教程',
... description: 'PHP 是一种创建动态交互性站点的强有力的服务器端脚本语言。',
... by:'xingweikun',
... url:'csdn',
... tags:['php'],
	likes:200
... })
WriteResult({ "nInserted" : 1 })
> db.col.insert({
... title:'Java教程',
... description: 'Java 是由Sun Microsystems公司于1995年5月推出的高级程序设计语言。',
... by:'xingweikun',
... url:'csdn',
... tags:['java'],
... likes:100
... })
WriteResult({ "nInserted" : 1 })
> db.col.insert({
... title:'MongoDB教程',
... description: 'MongoDB 是一个 Nosql 数据库',
... by:'xingweikun',
... url:'csdn',
... tags:['mongodb'],
... likes:150
... })
WriteResult({ "nInserted" : 1 })
>
> db.col.find()
{ "_id" : ObjectId("618d179d3b9d6667df7882b3"), "title" : "PHP教程", "description" : "PHP 是一种创建动态交互性站点的强有力的服务器端脚本语言。", "by" : "xingweikun", "url" : "csdn", "tags" : [ "php" ], "likes" : 200 }
{ "_id" : ObjectId("618d18da54bd2cbca7572cbd"), "title" : "Java教程", "description" : "Java 是由Sun Microsystems公司于1995年5月推出的高级程序设计语言。", "by" : "xingweikun", "url" : "csdn", "tags" : [ "java" ], "likes" : 100 }
{ "_id" : ObjectId("618d194854bd2cbca7572cbe"), "title" : "MongoDB教程", "description" : "MongoDB 是一个 Nosql 数据库", "by" : "xingweikun", "url" : "csdn", "tags" : [ "mongodb" ], "likes" : 150 }
>

如果想获取 “col” 集合中 title 为 String 的数据,你可以使用以下命令:

> db.col.find({"title":{$type:2}})
{ "_id" : ObjectId("618d179d3b9d6667df7882b3"), "title" : "PHP教程", "description" : "PHP 是一种创建动态交互性站点的强有力的服务器端脚本语言。", "by" : "xingweikun", "url" : "csdn", "tags" : [ "php" ], "likes" : 200 }
{ "_id" : ObjectId("618d18da54bd2cbca7572cbd"), "title" : "Java教程", "description" : "Java 是由Sun Microsystems公司于1995年5月推出的高级程序设计语言。", "by" : "xingweikun", "url" : "csdn", "tags" : [ "java" ], "likes" : 100 }
{ "_id" : ObjectId("618d194854bd2cbca7572cbe"), "title" : "MongoDB教程", "description" : "MongoDB 是一个 Nosql 数据库", "by" : "xingweikun", "url" : "csdn", "tags" : [ "mongodb" ], "likes" : 150 }
>
>> db.col.find({"title":{$type:'string'}})
{ "_id" : ObjectId("618d179d3b9d6667df7882b3"), "title" : "PHP教程", "description" : "PHP 是一种创建动态交互性站点的强有力的服务器端脚本语言。", "by" : "xingweikun", "url" : "csdn", "tags" : [ "php" ], "likes" : 200 }
{ "_id" : ObjectId("618d18da54bd2cbca7572cbd"), "title" : "Java教程", "description" : "Java 是由Sun Microsystems公司于1995年5月推出的高级程序设计语言。", "by" : "xingweikun", "url" : "csdn", "tags" : [ "java" ], "likes" : 100 }
{ "_id" : ObjectId("618d194854bd2cbca7572cbe"), "title" : "MongoDB教程", "description" : "MongoDB 是一个 Nosql 数据库", "by" : "xingweikun", "url" : "csdn", "tags" : [ "mongodb" ], "likes" : 150 }
>

MongoDB Limit与Skip方法

MongoDB Limit() 方法

显示查询文档中的两条记录

> db.col.find({},{"title":1,_id:0}).limit(2)
{ "title" : "PHP教程" }
{ "title" : "Java教程" }
> db.col.find({},{"description":1,_id:0}).limit(2)
{ "description" : "PHP 是一种创建动态交互性站点的强有力的服务器端脚本语言。" }
{ "description" : "Java 是由Sun Microsystems公司于1995年5月推出的高级程序设计语言。" }
>

MongoDB Skip() 方法

只显示第二条文档数据

> db.col.find({},{"title":1,_id:0}).limit(1).skip(1)
{ "title" : "Java教程" }
> db.col.find({},{"title":1,_id:0}).limit(1).skip(2)
{ "title" : "MongoDB教程" }
>

MongoDB 排序

MongoDB sort() 方法
col 集合中的数据按字段 likes 的降序排列:

> db.col.find({},{"title":1,_id:0}).sort({"likes":-1})
{ "title" : "PHP教程" }
{ "title" : "MongoDB教程" }
{ "title" : "Java教程" }

col 集合中的数据按字段 likes 的升序排列:

> db.col.find({},{"title":1,_id:0}).sort({"likes":1})
{ "title" : "Java教程" }
{ "title" : "MongoDB教程" }
{ "title" : "PHP教程" }
>

MongoDB 游标

方法名作用
hasNext判断是否有更多的文档
next用来获取下一条文档
toArray将查询结果放到数组中
count查询的结果为文档的总数量
limit限制查询结果返回数量
skip跳过指定数目的文档
sort对查询结果进行排序
objsLeftlnBatch查看当前批次剩余的未被迭代的文档数量
addOption为游标设置辅助选项,修改游标的默认行为
hint为查询强制使用指定索引
explain用于获取查询执行过程报告
snapshot对查询结果使用快照
> use xwk
switched to db xwk
> show collections
bjx
col
students
> var cursor=db.col.find()
> while (cursor.hasNext()){
... var doc=cursor.next();
... print(doc.name);
... print(doc)
... printjson(doc);
... }


[unknown type]
[object BSON]
{
        "_id" : ObjectId("618d179d3b9d6667df7882b3"),
        "title" : "PHP教程",
        "description" : "PHP 是一种创建动态交互性站点的强有力的服务器端脚本语言。",
        "by" : "xingweikun",
        "url" : "csdn",
        "tags" : [
                "php"
        ],
        "likes" : 200
}
[unknown type]
[object BSON]
{
        "_id" : ObjectId("618d18da54bd2cbca7572cbd"),
        "title" : "Java教程",
        "description" : "Java 是由Sun Microsystems公司于1995年5月推出的高级程序设计语言。",
        "by" : "xingweikun",
        "url" : "csdn",
        "tags" : [
                "java"
        ],
        "likes" : 100
}
[unknown type]
[object BSON]
{
        "_id" : ObjectId("618d194854bd2cbca7572cbe"),
        "title" : "MongoDB教程",
        "description" : "MongoDB 是一个 Nosql 数据库",
        "by" : "xingweikun",
        "url" : "csdn",
        "tags" : [
                "mongodb"
        ],
        "likes" : 150
}
>

MongoDB 索引

索引通常能够极大的提高查询的效率,如果没有索引,MongoDB在读取数据时必须扫描集合中的每个文件并选取那些符合查询条件的记录。

这种扫描全集合的查询效率是非常低的,特别在处理大量的数据时,查询可以要花费几十秒甚至几分钟,这对网站的性能是非常致命的。

索引是特殊的数据结构,索引存储在一个易于遍历读取的数据集合中,索引是对数据库表中一列或多列的值进行排序的一种结构。

MongoDB的索引是基于B-tree数据结构及对应算法形成的。树索引存储特定字段或字段集的值,按字段值排序

MongoDB在创建集合时,会默认在_id字段上创建唯一索引。该索引可防止客户端插入具有相同字段的两个文档,_id字段上的索引不能被删除。在分片集群中,如果不将该_id字段用作分片键,则应用需要自定义逻辑来确保_id 字段中值的唯一性,通常通过使用标准的自生成的Objectld作为_id。

索引类型

单键索引

db.collection.createIndex({key:1})//1为升序,-1为降序
> db.records.insert(
... {
... "score":1034,
... "location":{state:"NY",city:"New York"}
... }
... )
WriteResult({ "nInserted" : 1 })
> db.records.createIndex({score:1})
> db.records.find({score:1034})
{ "_id" : ObjectId("618dec2a1d5efac384051bdf"), "score" : 1034, "location" : { "state" : "NY", "city" : "New York" } }
>
查看查询过程
> db.records.find({score:1034}).explain()

复合索引

注意顺序,顺序不同将导致查询的结果也不同

> db.records.createIndex({"score":1,"location.state":1})
{
        "numIndexesBefore" : 2,
        "numIndexesAfter" : 3,
        "createdCollectionAutomatically" : false,
        "ok" : 1
}
>

多键值索引

> db.survey.insert({item:"ABC",ratings:[2,5,9]})
WriteResult({ "nInserted" : 1 })
> db.servey.createIndex({ratings:1})
{
        "numIndexesBefore" : 1,
        "numIndexesAfter" : 2,
        "createdCollectionAutomatically" : true,
        "ok" : 1
}

地理索引

> db.places.insert(
... {
... loc:{type:"Point",coordinates:[-73.97,40.77]},
... name:"Central Park",
... category:"Parks"
... }
... )
WriteResult({ "nInserted" : 1 })
> db.places.insert(
... {
... loc:{type:"Point",coordinates:[-73.88,40.78]},
... name:"La Guardia Airport",
... category:"Airport"
... }
... )
WriteResult({ "nInserted" : 1 })
> db.places.createIndex({loc:"2dsphere"})
{
        "numIndexesBefore" : 1,
        "numIndexesAfter" : 2,
        "createdCollectionAutomatically" : false,
        "ok" : 1
}
>

索引操作

查看现有索引

> db.records.getIndexes()
[
        {
                "v" : 2,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_"
        },
        {
                "v" : 2,
                "key" : {
                        "score" : 1
                },
                "name" : "score_1"
        },
        {
                "v" : 2,
                "key" : {
                        "score" : 1,
                        "location.state" : 1
                },
                "name" : "score_1_location.state_1"
        }
]
>

列出数据库的所有索引

> db.getCollectionNames().forEach(function(collection)
... {
... indexes=db[collection].getIndexes();
... print("Indexes for "+collection +":");
... printjson(indexes);
... });
Indexes for bjx:
[
        {
                "v" : 2,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_",
                "collation" : {
                        "locale" : "zh",
                        "caseLevel" : false,
                        "caseFirst" : "off",
                        "strength" : 3,
                        "numericOrdering" : false,
                        "alternate" : "non-ignorable",
                        "maxVariable" : "punct",
                        "normalization" : false,
                        "backwards" : false,
                        "version" : "57.1"
                }
        }
]
Indexes for col:
[
        {
                "v" : 2,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_"
        },
        {
                "v" : 2,
                "key" : {
                        "likes" : 1
                },
                "name" : "likes_1"
        }
]
Indexes for places:
[
        {
                "v" : 2,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_"
        },
        {
                "v" : 2,
                "key" : {
                        "loc" : "2dsphere"
                },
                "name" : "loc_2dsphere",
                "2dsphereIndexVersion" : 3
        }
]
Indexes for records:
[
        {
                "v" : 2,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_"
        },
        {
                "v" : 2,
                "key" : {
                        "score" : 1
                },
                "name" : "score_1"
        },
        {
                "v" : 2,
                "key" : {
                        "score" : 1,
                        "location.state" : 1
                },
                "name" : "score_1_location.state_1"
        }
]
Indexes for servey:
[
        {
                "v" : 2,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_"
        },
        {
                "v" : 2,
                "key" : {
                        "ratings" : 1
                },
                "name" : "ratings_1"
        }
]
Indexes for students:
[ { "v" : 2, "key" : { "_id" : 1 }, "name" : "_id_" } ]
Indexes for survey:
[ { "v" : 2, "key" : { "_id" : 1 }, "name" : "_id_" } ]

查看集合索引大小

> db.records.totalIndexSize()
61440
>

删除索引

删除集合指定索引

> db.records.dropIndex({"score":-1})
{
        "ok" : 0,
        "errmsg" : "can't find index with key: { score: -1.0 }",
        "code" : 27,
        "codeName" : "IndexNotFound"
}
>

没有这个索引,索引一定要写对名称和升序降序

> db.records.dropIndex({"score":1})
{ "nIndexesWas" : 3, "ok" : 1 }
>

这样写就对了

删除集合所有索引

> db.col.dropIndexes()
{
        "nIndexesWas" : 2,
        "msg" : "non-_id indexes dropped for collection",
        "ok" : 1
}
>

修改索引

修改索引,则要删除现有索引并重新创建索引

MongoDB 聚合

聚合管道方法

类似于mysql中的

select cust_id as _id,sum(amount) as total from orders where status like "%A%" group by cust_id;
> db.articles.insert([
... {"_id":10,"author":"dave","score":80,"views":100}MongoDB PHP

ios - Heroku 和 MongoDb 上的自定义解析服务器错误 3080:JSON 文本没有以数组或对象开头,并且允许未设置片段的选项

[Go] 通过 17 个简短代码片段,切底弄懂 channel 基础

mongodb关联查询

无法在 MongoDB(猫鼬)文档中追加数组

201555332盛照宗—网络对抗实验1—逆向与bof基础