mongodb-9.数据库连接,集合创建

数据库连接

mongodb URL

mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]

语法说明如下:

  • mongodb://:这是固定的格式,必须要指定;
  • username:password@:可选项,如果设置,在连接数据库服务器之后,驱动会尝试以给出的用户名(username)和密码(password)登录这个数据库;
  • host1:必填参数,用来指定要连接服务器的地址,如果要连接复制集,则需要指定多个主机地址;
  • portX:可选项,用来指定端口,如果不填,默认为 27017; /database:可选项,如果指定了
  • username:password@,则连接并验证登录指定的数据库,若不指定,则默认打开 test 数据库;
  • ?options:可选项,用来定义连接选项,连接选项的可选值如下表所示,如果不使用
  • /database,则前面需要使用/与前面的内容分隔,所有连接选项都是键值对 name=value
    的形式,键值对之间通过&或;(分号)隔开。

在这里插入图片描述

下面通过一些简单的示例来演示一下:

连接到一个运行在本机的,端口为 27017 的 MongoDB:

mongodb://localhost

连接到一个运行在本机的,端口为 27017 的 MongoDB,并以用户名"fred"和密码"foobar"登录,登录后将默认使用 admin 数据库:

mongodb://fred:foobar@localhost

连接到一个运行在本机的,端口为 27017 的 MongoDB,并以用户名"fred"和密码"foobar"登录,登录后使用 baz 数据库:

mongodb://fred:foobar@localhost/baz

连接到一个 replica pair,一台服务器在 c.biancheng.net,另一台在 www.biancheng.net:

mongodb://c.biancheng.net:27017,www.biancheng.net:27017

连接到本机的一个 replica set,端口分别为 27017、27018、27019:

mongodb://localhost,localhost:27018,localhost:27019

连接 replica set 中的三台服务器, 写入操作应用在主服务器 并且分布查询到从服务器:

mongodb://host1,host2,host3/?slaveOk=true

直接连接第一个服务器,无论该服务器是否为 replica set 的一部分,也无论它是主服务器还是从服务器:

mongodb://host1,host2,host3/?connect=direct;slaveOk=true

注意:上述的连接主要用于在您偏好使用某台服务器,但又有可供替换的服务器时。

使用安全模式连接到 localhost:

mongodb://localhost/?safe=true

以安全模式连接到 replica set,并且等待至少两个复制服务器成功写入,超时时间设置为 2 秒:

mongodb://host1,host2,host3/?safe=true;w=2;wtimeoutMS=2000

集合创建

db.createCollection(name, options)

参数说明如下:
name: 要创建的集合名称;
options: 可选参数, 指定有关内存大小及索引的选项,可选值如下表所示:

在这里插入图片描述
当我们在集合中插入文档时,MongoDB 会首先检查固定集合的 size 字段,然后检查 max 字段。

> db.createCollection("mycol", { capped : true, autoIndexId : true, size : 102400, max : 1000 } )
{
    "note" : "the autoIndexId option is deprecated and will be removed in a future release",
    "ok" : 1
}
> show tables
mycol

删除集合

db.mycol.drop()

循环插入

rsb:PRIMARY> for(var i=1;i<=10;i++){
... db.user.insert({name:"user"+i,age:20+i,phone:"18900898777"})
... }
WriteResult({ "nInserted" : 1 })

此外,还有insertOne,insertMany

查询

db.mycol.insert([
... {
... title: "MongoDB教程",
... description: "MongoDB 是一个 Nosql 数据库",
... by: "编程帮",
... url: "http://www.biancheng.net",
... tags: ["mongodb", "database", "NoSQL"],
... likes: 999
... },
... {
... title: "NoSQL数据库",
... description: "NoSQL数据库中没有数据表",
... by: "编程帮",
... url: "http://www.biancheng.net",
... tags: ["mongodb", "database", "NoSQL"],
... likes: 100,
... comments: [
...     {
...         user:"admin",
...         message: "第一个评论",
...         dateCreated: new Date(2021,01,10,2,35),
...         like: 0
...     }
... ]
... }
... ])

db.mycol.find()
db.collection_name.find(query, projection).pretty()
db.mycol.find().pretty()
db.mycol.findOne({title:“MongoDB教程”})
在这里插入图片描述

删除

db.collection_name.remove(
    <query>,
    {
        justOne: <boolean>,
        writeConcern: <document>
    }
)

例如

db.course.remove({‘title’:‘MongoDB教程’},{justOne:true})

全量删除

db.course.remove({})
db.course.count() 此时个数是0

查询显示指定字段

rsb:PRIMARY> db.mycol.find()
{ "_id" : ObjectId("63aa8fdd15d5e335bebf0172"), "title" : "MongoDB", "description" : "MongoDB  Nosql ", "by" : "", "url" : "http://www.biancheng.net", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 999 }
{ "_id" : ObjectId("63aa8fdd15d5e335bebf0173"), "title" : "NoSQL", "description" : "NoSQL荼", "by" : "", "url" : "http://www.biancheng.net", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100, "comments" : [ { "user" : "admin", "message" : "", "dateCreated" : ISODate("2021-02-09T18:35:00Z"), "like" : 0 } ] }
rsb:PRIMARY> db.mycol.find({},{title:1})
{ "_id" : ObjectId("63aa8fdd15d5e335bebf0172"), "title" : "MongoDB" }
{ "_id" : ObjectId("63aa8fdd15d5e335bebf0173"), "title" : "NoSQL" }
rsb:PRIMARY> db.mycol.find({},{title:1,_id:0})
{ "title" : "MongoDB" }
{ "title" : "NoSQL" }
rsb:PRIMARY> 

限制查询条数 limit ,skip

rsb:PRIMARY> db.course.find().limit(1)
{ "_id" : ObjectId("63aa958d6921a45cb71a7af8"), "title" : "MongoDB", "author" : "", "url" : "http://www.biancheng.com/mongodb/index.html" }
rsb:PRIMARY> db.course.find()
{ "_id" : ObjectId("63aa958d6921a45cb71a7af8"), "title" : "MongoDB", "author" : "", "url" : "http://www.biancheng.com/mongodb/index.html" }
{ "_id" : ObjectId("63aa958d6921a45cb71a7af9"), "title" : "HTML", "author" : "", "url" : "http://www.biancheng.com/html/index.html" }
{ "_id" : ObjectId("63aa958d6921a45cb71a7afa"), "title" : "C#", "author" : "", "url" : "http://www.biancheng.com/csharp/index.html" }
rsb:PRIMARY> db.course.find().skip(3)
rsb:PRIMARY> db.course.find().skip(2)
{ "_id" : ObjectId("63aa958d6921a45cb71a7afa"), "title" : "C#", "author" : "", "url" : "http://www.biancheng.com/csharp/index.html" }
rsb:PRIMARY> db.course.find().skip(0)
{ "_id" : ObjectId("63aa958d6921a45cb71a7af8"), "title" : "MongoDB", "author" : "", "url" : "http://www.biancheng.com/mongodb/index.html" }
{ "_id" : ObjectId("63aa958d6921a45cb71a7af9"), "title" : "HTML", "author" : "", "url" : "http://www.biancheng.com/html/index.html" }
{ "_id" : ObjectId("63aa958d6921a45cb71a7afa"), "title" : "C#", "author" : "", "url" : "http://www.biancheng.com/csharp/index.html" }
rsb:PRIMARY> db.course.count()
3

排序

rsb:PRIMARY> db.course.find({},{_id:0,title:1}).sort({})  默认按照_id升序排列
{ "title" : "MongoDB" }
{ "title" : "HTML" }
{ "title" : "C#" }
rsb:PRIMARY> db.course.find({},{_id:0,title:1}).sort({title:-1}) 按照title降序排序
{ "title" : "MongoDB" }
{ "title" : "HTML" }
{ "title" : "C#" }
rsb:PRIMARY> db.course.find({},{_id:0,title:1}).sort({title:1})
{ "title" : "C#" }
{ "title" : "HTML" }
{ "title" : "MongoDB" }

索引创建

rsb:PRIMARY> db.course.createIndex({title:1})
{
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 1,
        "numIndexesAfter" : 2,
        "commitQuorum" : "votingMembers",
        "ok" : 1,
        "$clusterTime" : {
                "clusterTime" : Timestamp(1672124587, 7),
                "signature" : {
                        "hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
                        "keyId" : NumberLong(0)
                }
        },
        "operationTime" : Timestamp(1672124587, 7)
}
rsb:PRIMARY> db.course.getIndexes()
[
        {
                "v" : 2,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_"
        },
        {
                "v" : 2,
                "key" : {
                        "title" : 1
                },
                "name" : "title_1"
        }
]
rsb:PRIMARY> 

删除索引

rsb:PRIMARY> db.course.dropIndex({title:1}) --删除指定索引
{
        "nIndexesWas" : 2,
        "ok" : 1,
        "$clusterTime" : {
                "clusterTime" : Timestamp(1672124846, 1),
                "signature" : {
                        "hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
                        "keyId" : NumberLong(0)
                }
        },
        "operationTime" : Timestamp(1672124846, 1)
}
rsb:PRIMARY> db.course.getIndexes()
[ { "v" : 2, "key" : { "_id" : 1 }, "name" : "_id_" } ]
rsb:PRIMARY> 

db.collection_name.dropIndexes() 可以删除除了_id以外的所有索引

聚合查询

db.course.aggregate([{$group : {_id : "$author", sum : {$sum : 1}}}])
{ "_id" : "编程帮", "sum" : 3 }

上述示例类似于 SQL 语句中的SELECT author, count(*) FROM course GROUP BY author。

在这里插入图片描述

下面介绍了聚合框架中几个常用的操作:

$project:用于从集合中选择要输出的字段;
$match:用于过滤数据,只输出符合条件的文档,可以减少作为下一阶段输入的文档数量;
$group:对集合中的文档进行分组,可用于统计结果;
$sort:将输入文档进行排序后输出;
$skip:在聚合管道中跳过指定数量的文档,并返回余下的文档;
$limit:用来限制 MongoDB 聚合管道返回的文档数量;
$unwind:将文档中的某一个数组类型字段拆分成多条,每条包含数组中的一个值。

下面通过几个简单的示例来演示 MongoDB 中管道的使用:

使用 $project 来选择要输出的字段:

rsb:PRIMARY> db.course.aggregate({$project:{title:1,author:1}}).pretty()
{
        "_id" : ObjectId("63aa958d6921a45cb71a7af8"),
        "title" : "MongoDB",
        "author" : "BIANCHENGBANG"
}
{
        "_id" : ObjectId("63aa958d6921a45cb71a7af9"),
        "title" : "HTML",
        "author" : ""
}
{
        "_id" : ObjectId("63aa958d6921a45cb71a7afa"),
        "title" : "C#",
        "author" : ""
}
rsb:PRIMARY> 

使用$skip跳过指定的文档

rsb:PRIMARY> db.course.aggregate({$skip:2}).pretty()
{
        "_id" : ObjectId("63aa958d6921a45cb71a7afa"),
        "title" : "C#",
        "author" : "",
        "url" : "http://www.biancheng.com/csharp/index.html"
}
rsb:PRIMARY> 
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值