MongoDB学习笔记

来源:互联网 发布:impacket python 编辑:程序博客网 时间:2024/06/15 12:19

1、安装

1.1 下载

MongoDB的官网是:http://www.mongodb.org/ 。

如果需要下载,则可以在该地址下面下载:https://pan.baidu.com/s/1gfCNexl

解压后,新建两个文件夹db、log 如下图所示:


1.2安装

打开命令行执行:

Mongod.exe--dbpath=D:/handler/Mongodb/software/db/

--logpath=D:/handler/Mongodb/software/log/log.log

如下图:


安装完成之后打开任务管理器,如下图:


启动mongodb服务。

2、使用


2.1 简单使用

2.1.1获取数据库名称:

>db.getName()
test
当前数据库名称是test。

2.1.2创建数据库

> use java
switched to db java
使用一个名字叫做java的数据库,如果该数据库不存在,则创建。

如图:


2.1.3 删除数据库

db.dropDatabase():删除选定的数据库。如果没有选择任何数据库,那么它会删除默认的“test”数据库
show dbs检查可用数据库的列表

2.1.4 查看数据库结构

> db.stats()
{
"db" : "java",
"collections" : 0,
"views" : 0,
"objects" : 0,
"avgObjSize" : 0,
"dataSize" : 0,
"storageSize" : 0,
"numExtents" : 0,
"indexes" : 0,
"indexSize" : 0,
"fileSize" : 0,
"ok" : 1
}
参数解释:
"db" : " java " ,表示当前是针对" java "这个数据库的描述。想要查看其他数据库,可以先运行$ use databasename(e.g $use admiin).
 "collections" : 0,表示当前数据库有多少个collections.可以通过运行show collections查看当前数据库具体有哪些collection.
 "objects" : 0,表示当前数据库所有collection总共有多少行数据。显示的数据是一个估计值,并不是非常精确。
 "avgObjSize" :0,表示每行数据是大小,也是估计值,单位是bytes
 "dataSize" : 0,表示当前数据库所有数据的总大小,不是指占有磁盘大小。单位是bytes
 "storageSize" :0,表示当前数据库占有磁盘大小,单位是bytes,因为mongodb有预分配空间机制,为了防止当有大量数据插入时对磁盘的压力,因此会事先多分配磁盘空间。
 "numExtents" : 0,似乎没有什么真实意义。我弄明白之后再详细补充说明。
 "indexes" : 0 ,表示system.indexes表数据行数。
 "indexSize" : 0,表示索引占有磁盘大小。单位是bytes
"fileSize" : 0,表示当前数据库预分配的文件大小。

2.1.5 简单运算

> x=100
100
> y=200
200
> x+y
300

2.1.6 查看数据库和集合列表

1、查看数据库列表:show dbs();
2、查看集合列表:> show collections

2.1.7 创建集合

> db.createCollection("myCollection")
{ "ok" : 1 }
创建集合(带初始化参数)
capped:类型为boolean,如果为true则为创建一个固定大小的集合,当集合中的数据条目达到最大时自动覆盖以前的条目。
autoIndexID:类型为boolean,默认为false,如果设置为true,则会在_id上创建索引。
size:指定集合字节最大值,当capped为true时需要指定。单位为byte
max:指定集合中数据的最大条数。
例:
db.createCollection(
" myCollection",
{capped:1,autoIndexID:1,size:6142800,max:10000}
)
在MongoDB中并不需要创建集合。 当插入文档时 MongoDB 会自动创建集合。

2.1.8 删除集合

db. myCollection.drop();

2.1.9 查看数据库帮助信息

> db.help()

2.2写入数据

2.2.1 插入简单数据

要将数据插入到 MongoDB 集合中,需要使用 MongoDB 的 insert()或save()方法。
> db.goods.insert({name:'huawei01',price:1000,weight:135,number:35})
WriteResult({ "nInserted" : 1 })
使用db.goods.find()可以查看数据
> db.goods.find()
{ "_id" : ObjectId("5a0d98305c74f3c74efed7c5"), "name" : "huawei01", "price" : 1
000, "weight" : 135, "number" : 35 }
>

2.2.2 多维数据插入

> db.goods.insert({name:'huawei01',price:1000,weight:135,number:35,area:{provinc
e:'beijing',city:'beijing'}
})

2.3 查询

2.3.1 笼统数据查询

> db.goods.find ()
> db.goods.findOne()
要以格式化的方式显示结果,可以使用pretty()方法。
db.goods.find ().pretty()

2.3.2 条件限制查询

> db.goods.find({name:'huawei02'})

2.3.3范围条件查询

操作

语法

示例

等效语句

相等

{<key>:<value>}

db.myCollection.find({name:"huawei01"})

where name=huawei01

小于

{<key>:{$lt:<value>}}

db.myCollection.find({"price":{$lt:2000}})

where price<2000

小于等于

{<key>:{$lte:<value>}}

db.myCollection.find({"price":{$lte:1000}})

where price<=1000

大于

{<key>:{$gt:<value>}}

db.myCollection.find({"price":{$gt:1000}})

where price>1000

大于等于

{<key>:{$gte:<value>}}

db.myCollection.find({"price":{$gte:1000}})

Where price>=1000

不等于

{<key>:{$ne:<value>}}

db.myCollection.find({"price":{$ne:1000}})

where price!=1000


例:


2.3.4 设置多个查询条件

相当于关系型数据库中的and
db.数据库.find({条件,条件,条件})
例如:要求价格大于等于1000并且 重量 小于 134 的
db.myCollection.find({price:{ '$gte':1000},weight:{ '$lt':134}})
或者通过严格等于的条件进行复合查询
例如:数量为 100 并且 价格小于2000的
db.myCollection.find({number:{ '$lte':100},price:2000})

2.3.5 多维字段的查询

db.表.find({'key.name':值})

db.表.find({key.name :{ '$gt':值}})
db.表.find({key.name :{ '$gt':值}, key2.name2 :{ '$lt':值}})

2.3.5 数组条件的限制

db.表.find({字段(数组):val}) //数组元素值 有val 即可(存在一个元素)
例如:db.myCollection.find({color: 'red'})
db.表.find({字段(数组):{ '$all':[v1,v2]}}) //数组元素值 有v1和v2 即可(v1 和v2顺序不做要求)
例如:db.myCollection.find({color: {'$all':[ 'green', 'blank']}})

2.3.6 限制查询字段

db.表.find({条件},{字段:1/0,字段:1/0})
1 查询此字段
0 排除此字段
规则:要输出就全部输出,不输出就全部不输出 即 要是0全是0,要是1全是1。

2.3.7 $or 查询,多个条件,满足一个即可

db.myCollection.find({"$or":[price:2000},{num:{ '$lt':100}}]})

2.4 修改数据

db.表.update({条件},{'$set':{字段:值,字段:值……}})
db.表.update({条件},{字段:值,字段:值……})
1、有$set的修改:只修改设置的字段,其他字段不变
2、没有$set的修改:只修改设置的字段,其他字段删除。

2.5删除

2.5.1 删除记录

db.表.remove(条件)

2.5.2 删除字段

db.表.update({条件},{'$unset':{字段:1/0}})

3、Java 操作 MongoDB


pom.xml 文件内容如下:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">  <!--指定了当前pom的版本-->  <modelVersion>4.0.0</modelVersion> <!--属于哪个项目:反写公司网址+项目名-->  <groupId>com.hundsun.maven.mongodb</groupId>  <!--实际的项目名称:项目名+模块名-->  <artifactId>MongoDBToJava</artifactId>  <!--第一个0表示大版本号        第二个0表示分支版本号        第三个0表示小版本号        SNAPSHOT快照        alpha内部测试        beta公测        Release稳定        GA正式发布-->  <version>0.0.1-SNAPSHOT</version>  <!--打包方式,默认jar    war zip pom-->  <packaging>jar</packaging>  <!--项目描述名-->  <name>MongoDBToJava</name>  <!--项目地址-->  <url>http://maven.apache.org</url>  <properties>    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>  </properties><!--依赖坐标-->  <dependencies>    <dependency>      <groupId>junit</groupId>      <artifactId>junit</artifactId>      <version>3.8.1</version>      <scope>test</scope>    </dependency>
<dependency>            <groupId>org.mongodb</groupId>            <artifactId>mongodb-driver</artifactId>            <version>3.4.2</version>        </dependency>  </dependencies></project>

3.1 连接数据库

public class ConnectionMongodb {public static void main(String[] args) { try {            // 连接服务器            MongoClient mongoClient = new MongoClient("localhost", 27017);            //连接数据库            MongoDatabase mgdb = mongoClient.getDatabase("java");            System.out.println("Connect to database successfully!");            System.out.println("MongoDatabase inof is : "+mgdb.getName());        } catch (Exception e) {            System.err.println(e.getClass().getName() + ": " + e.getMessage());        }}}


3.2 查询数据库

3.2.1列出所有集合

public class SelectMongodb{public static void main(String[] args) { try {            MongoClient mongoClient = new MongoClient("localhost", 27017);            MongoDatabase database = mongoClient.getDatabase("java");            MongoCollection<Document> coll = database.getCollection("myCollection");                        System.out.println("Collection created successfully");            System.out.println("当前数据库中的所有集合是:");                        for (String name : database.listCollectionNames()) {                System.out.println(name);            }        } catch (Exception e) {            System.err.println(e.getClass().getName() + ": " + e.getMessage());        }}}

3.2.2创建集合

public class CreateCollection {public static void main(String[] args) { try {            MongoClient mongoClient = new MongoClient("localhost", 27017);            MongoDatabase database = mongoClient.getDatabase("java");            database.createCollection("NewCollection",new CreateCollectionOptions().capped(true).sizeInBytes(0x100000));            System.out.println("Collection created successfully");            System.out.println("当前数据库中的所有集合是:");            for (String name : database.listCollectionNames()) {                System.out.println(name);            }        } catch (Exception e) {            System.err.println(e.getClass().getName() + ": " + e.getMessage());        }}}



3.3 插入数据库

3.3.1插入单行

public class InsertMongoDb {public static void main(String[] args) { try {            MongoClient mongoClient = new MongoClient("localhost", 27017);            MongoDatabase database = mongoClient.getDatabase("java");            // database.createCollection("NewCollection", new            // CreateCollectionOptions().capped(true).sizeInBytes(0x100000));            System.out.println("Collection created successfully");            System.out.println("当前数据库中的所有集合是:");            for (String name : database.listCollectionNames()) {                System.out.println(name);            }            MongoCollection coll = database.getCollection("NewCollection");            System.out.println("Collection NewCollection selected successfully");            MongoCollection<Document> collection = database.getCollection("NewCollection");            Document document = new Document("_id", 1111).append("title", "MongoDB Insert Demo")                    .append("description","database")                    .append("likes", 30)                    .append("by", "yiibai point");            collection.insertOne(document);            collection.find().forEach(printBlock);            System.out.println("Document inserted successfully");        } catch (Exception e) {            System.err.println(e.getClass().getName() + ": " + e.getMessage());        }    } static Block<Document> printBlock = new Block<Document>() {        public void apply(final Document document) {            System.out.println(document.toJson());        }    };}


3.3.2插入多行

Document doc1 = new Document("name", "Amarcord Pizzeria")                    .append("contact", new Document("phone", "264-555-0193")                                            .append("email", "amarcord.pizzeria@example.net")                                            .append("location",Arrays.asList(-73.88502, 40.749556)))                    .append("stars", 2)                    .append("categories", Arrays.asList("Pizzeria", "Italian", "Pasta"));     Document doc2 = new Document("name", "Blue Coffee Bar")                    .append("contact", new Document("phone", "604-555-0102")                                            .append("email", "bluecoffeebar@example.com")                                            .append("location",Arrays.asList(-73.97902, 40.8479556)))                    .append("stars", 5)                    .append("categories", Arrays.asList("Coffee", "Pastries"));     List<Document> documents = new ArrayList<Document>();     documents.add(doc1);     documents.add(doc2);     collection.insertMany(documents);

3.4 更新数据库

public class UpdateMongoDb {public static void main(String[] args) {try {            MongoClient mongoClient = new MongoClient("127.0.0.1", 27017);            MongoDatabase database = mongoClient.getDatabase("java");            System.out.println("MongoDatabase inof is : "+database.getName());            MongoCollection<Document> collection = database.getCollection("NewCollection");               Document filter = new Document();              filter.append("_id", 1111);              Document update = new Document();              update.append("$set", new Document("title", "更新了标题titl"));              UpdateResult result = updateOne(collection,filter, update);                                      collection.find().forEach(printBlock);        } catch (Exception e) {            System.err.println(e.getClass().getName() + ": " + e.getMessage());        }}private static UpdateResult updateOne(MongoCollection<Document> collection,Document filter, Document update) {UpdateResult result = collection.updateOne(filter, update);            return result;  }static Block<Document> printBlock = new Block<Document>() {        public void apply(final Document document) {            System.out.println(document.toJson());        }    };}


3.5删除表

public class DeleteMongoDb {public static void main(String[] args) {try {            MongoClient mongoClient = new MongoClient("127.0.0.1", 27017);            MongoDatabase database = mongoClient.getDatabase("java");            System.out.println("Connect to database successfully!");            System.out.println("MongoDatabase inof is : "+database.getName());            MongoCollection<Document> collection = database.getCollection("myCollection");             collection.find().forEach(printBlock);            // 删除文档            collection.deleteOne(new Document().append("name", "huawei01"));            System.out.println("After Delete Document:");            collection.find().forEach(printBlock);        } catch (Exception e) {            System.err.println(e.getClass().getName() + ": " + e.getMessage());        }    }    static Block<Document> printBlock = new Block<Document>() {        public void apply(final Document document) {            System.out.println(document.toJson());        }    };}


4 账号权限

4.1 创建三个权限账号

账号:
1、”root”:root 管理员账号(admin数据库) 可以 读、写
2、”zhangys:123456” 普通账号(java数据库) 可以读、写
3、”xiaohong:1234”普通账号(java数据库)权限说明:只可以读
普通账号:只能操作本身数据库
管理员账号:可以操作全部数据库
账号设置的顺序:
1、必须先设置 root 管理员账号
2、其次再设置普通账号 zhangys和xiaohong
创建账号指令:
db.createUser
第一步:使用use admin数据库,创建root管理员账号
> use admin
switched to db admin
> db.createUser({user:"zhangys",pwd:"123456",roles:[{role:"root",db:"admin"}]})


创建普通用户(可读可写):
db.createUser({user:"zhangys",pwd:"123456",roles:[{role:"root",db:"admin"}]})

创建普通用户(只读):
db.createUser({user:"xiaohong",pwd:"1234",roles:["read"]})






原创粉丝点击