【MongoDB】01、MongoDB基础
一、MongoDB概述1、MogoDB简介
什么是MongoDB ?
MongoDB 是由C++语言编写的,是一个基于分布式文件存储的开源数据库系统。
在高负载的情况下,添加更多的节点,可以保证服务器性能。
MongoDB 旨在为WEB应用提供可扩展的高性能数据存储解决方案。
MongoDB 将数据存储为一个文档,数据结构由键值(key=>value)对组成。MongoDB 文档类似于 JSON 对象。字段值可以包含其他文档,数组及文档数组。
一个文档相当于mysql数据库中的一行数据
2007年10月,MongoDB由10gen团队所发展。2009年2月首度推出。
[*] 2012年05月23日,MongoDB2.1 开发分支发布了! 该版本采用全新架构,包含诸多增强。
[*] 最新稳定版:3.4.2
2、MongoDB特点
主要特点
[*] MongoDB的提供了一个面向文档存储,操作起来比较简单和容易。
[*] 你可以在MongoDB记录中设置任何属性的索引 (如:FirstName="Sameer",Address="8 Gandhi Road")来实现更快的排序。
[*] 你可以通过本地或者网络创建数据镜像,这使得MongoDB有更强的扩展性。
[*] 如果负载的增加(需要更多的存储空间和更强的处理能力) ,它可以分布在计算机网络中的其他节点上这就是所谓的分片。(自动分片)
[*] Mongo支持丰富的查询表达式。查询指令使用JSON形式的标记,可轻易查询文档中内嵌的对象及数组。
[*] MongoDb 使用update()命令可以实现替换完成的文档(数据)或者一些指定的数据字段 。
[*] Mongodb中的Map/reduce主要是用来对数据进行批量处理和聚合操作。
[*] Map和Reduce。Map函数调用emit(key,value)遍历集合中所有的记录,将key与value传给Reduce函数进行处理。
[*] Map函数和Reduce函数是使用Javascript编写的,并可以通过db.runCommand或mapreduce命令来执行MapReduce操作。
[*] GridFS是MongoDB中的一个内置功能,可以用于存放大量小文件。内置分布式文件系统
[*] MongoDB允许在服务端执行脚本,可以用Javascript编写某个函数,直接在服务端执行,也可以把函数的定义存储在服务端,下次直接调用即可。
[*] MongoDB支持各种编程语言:RUBY,PYTHON,JAVA,C++,PHP,C#等多种语言。
[*] MongoDB安装简单。
二、概念解析
不管我们学习什么数据库都应该学习其中的基础概念,在mongodb中基本的概念是文档、集合、数据库,下面我们挨个介绍。下表将帮助您更容易理解Mongo中的一些概念:
SQL术语/概念MongoDB术语/概念解释/说明databasedatabase数据库tablecollection数据库表/集合rowdocument数据记录行/文档columnfield数据字段/域indexindex索引table joins表连接,MongoDB不支持primary keyprimary key主键,MongoDB自动将_id字段设置为主键 通过下图实例,我们也可以更直观的的了解Mongo中的一些概念:
文档
文档是一个键值(key-value)对(即BSON)。MongoDB 的文档不需要设置相同的字段,并且相同的字段不需要相同的数据类型,这与关系型数据库有很大的区别,也是 MongoDB 非常突出的特点。
一个简单的文档例子如下:
{"site":"www.runoob.com", "name":"菜鸟教程"} 需要注意的是:
[*] 文档中的键/值对是有序的。
[*] 文档中的值不仅可以是在双引号里面的字符串,还可以是其他几种数据类型(甚至可以是整个嵌入的文档)。
[*] MongoDB区分类型和大小写。
[*] MongoDB的文档不能有重复的键。
[*] 文档的键是字符串。除了少数例外情况,键可以使用任意UTF-8字符。
文档键命名规范:
[*] 键不能含有\0 (空字符)。这个字符用来表示键的结尾。
[*] .和$有特别的意义,只有在特定环境下才能使用。
[*] 以下划线"_"开头的键是保留的(不是严格要求的)。
每个文档都有隐藏的_id键也就是字段,相当于mysql中的主键
集合
集合就是 MongoDB 文档组,类似于 RDBMS (关系数据库管理系统:Relational Database Management System)中的表格。集合存在于数据库中,集合没有固定的结构,这意味着你在对集合可以插入不同格式和类型的数据,但通常情况下我们插入集合的数据都会有一定的关联性。
比如,我们可以将以下不同数据结构的文档插入到集合中:
{"site":"www.baidu.com"}
{"site":"www.google.com","name":"Google"}
{"site":"www.runoob.com","name":"菜鸟教程","num":5}
当第一个文档插入时,集合就会被创建。
合法的集合名
[*] 集合名不能是空字符串""。
[*] 集合名不能含有\0字符(空字符),这个字符表示集合名的结尾。
[*] 集合名不能以"system."开头,这是为系统集合保留的前缀。
[*] 用户创建的集合名字不能含有保留字符。有些驱动程序的确支持在集合名里面包含,这是因为某些系统生成的集合中包含该字符。除非你要访问这种系统创建的集合,否则千万不要在名字里出现$。
如下实例:
db.col.findOne()capped collections
Capped collections 就是固定大小的collection。
它有很高的性能以及队列过期的特性(过期按照插入的顺序). 有点和 "RRD" 概念类似。
Capped collections是高性能自动的维护对象的插入顺序。它非常适合类似记录日志的功能 和标准的collection不同,你必须要显式的创建一个capped collection, 指定一个collection的大小,单位是字节。collection的数据存储空间值提前分配的。
要注意的是指定的存储大小包含了数据库的头信息。
db.createCollection("mycoll", {capped:true, size:100000})
[*] 在capped collection中,你能添加新的对象。
[*] 能进行更新,然而,对象不会增加存储空间。如果增加,更新就会失败 。
[*] 数据库不允许进行删除。使用drop()方法删除collection所有的行。
[*] 注意: 删除之后,你必须显式的重新创建这个collection。
[*] 在32bit机器中,capped collection最大存储为1e9( 1X109)个字节。
[*]
数据库
一个mongodb中可以建立多个数据库。
MongoDB的单个实例可以容纳多个独立的数据库,每一个都有自己的集合和权限,不同的数据库也放置在不同的文件中。
"show dbs" 命令可以显示所有数据的列表。
执行 "db" 命令可以显示当前数据库对象或集合。
运行"use db_name"命令,可以使用一个指定的数据库。
数据库也通过名字来标识。数据库名可以是满足以下条件的任意UTF-8字符串。
[*] 不能是空字符串("")。
[*] 不得含有' '(空格)、.、$、/、\和\0 (空宇符)。
[*] 应全部小写。
[*] 最多64字节。
[*]
元数据
数据库的信息是存储在集合中。它们使用了系统的命名空间:
dbname.system.* 在MongoDB数据库中名字空间 .system.* 是包含多种系统信息的特殊集合(Collection),如下:
集合命名空间描述dbname.system.namespaces列出所有名字空间。dbname.system.indexes列出所有索引。dbname.system.profile包含数据库概要(profile)信息。dbname.system.users列出所有可访问数据库的用户。dbname.local.sources包含复制对端(slave)的服务器信息和状态。 对于修改系统集合中的对象有如下限制。
在`system`.`indexes`插入数据,可以创建索引。但除此之外该表信息是不可变的(特殊的drop index命令将自动更新相关信息)。
`system`.`users`是可修改的。 `system`.`profile`是可删除的。
MongoDB 数据类型
下表为MongoDB中常用的几种数据类型。
数据类型描述String字符串。存储数据常用的数据类型。在 MongoDB 中,UTF-8 编码的字符串才是合法的。Integer整型数值。用于存储数值。根据你所采用的服务器,可分为 32 位或 64 位。Boolean布尔值。用于存储布尔值(真/假)。Double双精度浮点值。用于存储浮点值。Min/Max keys将一个值与 BSON(二进制的 JSON)元素的最低值和最高值相对比。Arrays用于将数组或列表或多个值存储为一个键。Timestamp时间戳。记录文档修改或添加的具体时间。Object用于内嵌文档。Null用于创建空值。Symbol符号。该数据类型基本上等同于字符串类型,但不同的是,它一般用于采用特殊符号类型的语言。Date日期时间。用 UNIX 时间格式来存储当前日期或时间。你可以指定自己的日期时间:创建 Date 对象,传入年月日信息。Object> 二、MongoDB安装
MongoDB官网上提供了各种版本的MongoDB安装包有rpm包,通用二进制包,源码包
1、yum安装
epel源中有2.4.14版本的MongoDB,就直接yum安装了
# yum list|grep "^mongodb"
mongodb.x86_64 2.4.14-4.el6 epel
mongodb-server.x86_64 2.4.14-4.el6 epel
# yum install mongodb-server mongodb
# rpm -ql mongodb-server
/etc/logrotate.d/mongodb
/etc/mongodb.conf
/etc/rc.d/init.d/mongod
/etc/sysconfig/mongod
/usr/bin/mongod
/usr/bin/mongos
/usr/share/man/man1/mongod.1.gz
/usr/share/man/man1/mongos.1.gz
/var/lib/mongodb
/var/log/mongodb
/var/run/mongodb
# rpm -ql mongodb
/usr/bin/bsondump
/usr/bin/mongo
/usr/bin/mongodump
/usr/bin/mongoexport
/usr/bin/mongofiles
/usr/bin/mongoimport
/usr/bin/mongooplog
/usr/bin/mongoperf
/usr/bin/mongorestore
/usr/bin/mongosniff
/usr/bin/mongostat
/usr/bin/mongotop
/usr/share/man/man1/bsondump.1.gz
2、启动mongod
# service mongod reload mongodb默认不启用认证功能:
3、客户端mongo的使用
mongo的用法:
# mongo --help
MongoDB shell version: 2.4.14
usage: mongo
db address can be:
foo foo database on local machine
192.169.0.5/foo foo database on 192.168.0.5 machine
192.169.0.5:9999/foofoo database on 192.168.0.5 machine on port 9999
options:
--shell run the shell after executing
files
--nodb don't connect to mongod on
startup - no 'db address' arg
expected
--norc will not run the ".mongorc.js"
file on start up
--quiet be less chatty
--port arg port to connect to
--host arg server to connect to
--eval arg evaluate javascript
-u [ --username ] arg username for authentication
-p [ --password ] arg password for authentication
--authenticationDatabase arg user source (defaults to dbname)
--authenticationMechanism arg (=MONGODB-CR) authentication mechanism
-h [ --help ] show this usage information
--version show version information
--verbose increase verbosity
--ipv6 enable IPv6 support (disabled by
default)
--ssl use SSL for all connections
--sslCAFile arg Certificate Authority for SSL
--sslPEMKeyFile arg PEM certificate/key file for SSL
--sslPEMKeyPassword arg password for key in PEM file for
SSL
实例:
# mongo --host 192.168.10.7
MongoDB shell version: 2.4.14
connecting to: 192.168.10.7:27017/test # 默认连入了test数据库
> help
db.help() help on db methods # 数据库相关的命令
db.mycoll.help() help on collection methods
# 集合相关的命令
sh.help() sharding helpers
rs.help() replica set helpers
help admin administrative help
help connect connecting to a db help
help keys key shortcuts
help misc misc things to know
help mr mapreduce
show dbs show database names # 显示已存在的数据库
show collections show collections in current database
# 显示已存在的表
show users show users in current database
show profile show most recent system.profile entries with time >= 1ms # 性能探测工具
show logs show the accessible logger names
show log prints out the last segment of log in memory, 'global' is default
use set current database
db.foo.find() list objects in collection foo
db.foo.find( { a : 1 } ) list objects in foo where a == 1
it result of the last line evaluated; use to further iterate
DBQuery.shellBatchSize = x set default number of items to display on shell
exit quit the mongo shell
> use mydb # mongodb比较诡异,数据库无须创建就可以先使用
switched to db mydb
> show dbs; # 并没有mydb库,当use某库后,在里面创建了表就会自动创建库
admin(empty)
local0.078125GB
test(empty)
常用命令:
help
db.help()
db.mycoll.help()
db.stats():数据库状态
db.serverStatus():mongodb数据库服务器状态
show dbs、show collections
db.getCollectionNames():显示当前数据所有集合的名称列表
三、CRUD快速入门
CRUD是指在做计算处理时的增加(Create)、读取查询(Retrieve)、更新(Update)和删除(Delete)几个单词的首字母简写。主要被用在描述软件系统中数据库或者持久层的基本操作功能。
Mongo支持丰富的查询表达式。查询指令使用JSON形式的标记,可轻易查询文档中内嵌的对象及数组。
JSON:JavaScript Object Notation
轻量级的XML,
json有两种结构:
名称/值对象的集合,
值的有序列表
1、插入文档
文档的数据结构和JSON基本一样,所有存储在集合中的数据都是BSON格式,BSON是一种类json的一种二进制形式的存储格式,简称Binary JSON。
MongoDB 使用 insert() ,语法如下:
db.COLLECTION_NAME.insert(document) 不需要先创建数据库和集合:数据库会自动延迟创建,集合不需要定义,所以可以直接插入数据
# mongo --host 192.168.10.7
MongoDB shell version: 2.4.14
connecting to: 192.168.10.7:27017/test
> show dbs
local0.078125GB
> use testdb
switched to db testdb
> show dbs
local0.078125GB
test(empty)
testdb0.203125GB
> db.stats()
{
"db" : "testdb",
"collections" : 0,
"objects" : 0,
"avgObjSize" : 0,
"dataSize" : 0,
"storageSize" : 0,
"numExtents" : 0,
"indexes" : 0,
"indexSize" : 0,
"fileSize" : 0,
"nsSizeMB" : 0,
"dataFileVersion" : {
},
"ok" : 1
}
> db.students.insert({name:"tom",age:23})
> show collections
students
system.indexes
> db.stats()
{
"db" : "testdb",
"collections" : 3,
"objects" : 5,
"avgObjSize" : 48,
"dataSize" : 240,
"storageSize" : 12288,
"numExtents" : 3,
"indexes" : 1,
"indexSize" : 8176,
"fileSize" : 201326592,
"nsSizeMB" : 16,
"dataFileVersion" : {
"major" : 4,
"minor" : 5
},
"ok" : 1
}
> db.students.stats() # 显示指定集合的状态
{
"ns" : "testdb.students", # 名称
"count" : 1,
"size" : 56,
"avgObjSize" : 56,
"storageSize" : 4096,
"numExtents" : 1,
"nindexes" : 1,
"lastExtentSize" : 4096,
"paddingFactor" : 1,
"systemFlags" : 1,
"userFlags" : 0,
"totalIndexSize" : 8176,
"indexSizes" : {
"_id_" : 8176
},
"ok" : 1
}
> db.getCollectionNames()
[ "students", "system.indexes" ]
2、查询文档
MongoDB 查询数据的语法格式如下:
db.COLLECTION_NAME.find()
查看db.COLLECTION_NAME.find()的帮助信息:
> db.a.find().help()
find() modifiers
.sort( {...} )
.limit( n )
.skip( n )
.count() - total # of objects matching query, ignores skip,limit
.size() - total # of objects cursor would return, honors skip,limit
.explain()
.hint(...)
.addOption(n) - adds op_query options -- see wire protocol
._addSpecial(name, value) - http://dochub.mongodb.org/core/advancedqueries#AdvancedQueries-Metaqueryoperators
.batchSize(n) - sets the number of docs to return per getMore
.showDiskLoc() - adds a $diskLoc field to each returned object
.min(idxDoc)
.max(idxDoc)
Cursor methods
.toArray() - iterates through docs and returns an array of the results
.forEach( func )
.map( func )
.hasNext()
.next()
.objsLeftInBatch() - returns count of docs left in current batch (when exhausted, a new getMore will be issued)
.count(applySkipLimit) - runs command at server
.itcount() - iterates through documents and counts them
find()简单的使用:
> db.students.find() # 需要在相应的集合下
{ "_id" : ObjectId("58d50e6376002e9a38ccceec"), "name" : "tom", "age" : 23 }
> db.students.find().count()
1
> db.students.count()
1
除了 find() 方法之外,还有一个 findOne() 方法,它只返回一个文档:
> db.students.findOne() # 只返回第一个,多次执行并不会向下
{ "_id" : ObjectId("58d50e6376002e9a38ccceec"), "name" : "tom", "age" : 23 }
> db.students.findOne()
{ "_id" : ObjectId("58d50e6376002e9a38ccceec"), "name" : "tom", "age" : 23 }
find()的高级用法
比较操作:$gt,$gte,$lt,$lte,$ne
操作格式范例RDBMS中的类似语句等于{:}db.col.find({"by":"菜鸟教程"})where by = '菜鸟教程'小于{:{$lt:}}db.col.find({"likes":{$lt:50}})where likes < 50小于或等于{:{$lte:}}db.col.find({"likes":{$lte:50}})where likes50大于或等于{:{$gte:}}db.col.find({"likes":{$gte:50}})where likes >= 50不等于{:{$ne:}}db.col.find({"likes":{$ne:50}})where likes != 50 实例:
> db.students.find()
{ "_id" : ObjectId("58d50e6376002e9a38ccceec"), "name" : "tom", "age" : 23 }
{ "_id" : ObjectId("58d5183976002e9a38ccceed"), "name" : "xj" }
{ "_id" : ObjectId("58d51b2776002e9a38ccceee"), "name" : "xx", "Age" : 35 }
{ "_id" : ObjectId("58d51cec76002e9a38ccceef"), "name" : "x1", "age" : 40 }
{ "_id" : ObjectId("58d51cff76002e9a38cccef0"), "name" : "x2", "age" : 50 }
> db.students.find({age:{$gt:30}})# 字符区分大小写
{ "_id" : ObjectId("58d51cec76002e9a38ccceef"), "name" : "x1", "age" : 40 }
{ "_id" : ObjectId("58d51cff76002e9a38cccef0"), "name" : "x2", "age" : 50 }
> db.students.find({age:{$lt:40}})
{ "_id" : ObjectId("58d50e6376002e9a38ccceec"), "name" : "tom", "age" : 23 }
> db.students.find({age:{$lte:40}})
{ "_id" : ObjectId("58d50e6376002e9a38ccceec"), "name" : "tom", "age" : 23 }
{ "_id" : ObjectId("58d51cec76002e9a38ccceef"), "name" : "x1", "age" : 40 }
$in 查找在指定列表中列出的数据
$nin
语法格式:
{filed:{$in:[]}}
> db.students.find()
{ "_id" : ObjectId("58d50e6376002e9a38ccceec"), "name" : "tom", "age" : 23 }
{ "_id" : ObjectId("58d5183976002e9a38ccceed"), "name" : "xj" }
{ "_id" : ObjectId("58d51b2776002e9a38ccceee"), "name" : "xx", "Age" : 35 }
{ "_id" : ObjectId("58d51cec76002e9a38ccceef"), "name" : "x1", "age" : 40 }
{ "_id" : ObjectId("58d51cff76002e9a38cccef0"), "name" : "x2", "age" : 50 }
{ "_id" : ObjectId("58d51f0e76002e9a38cccef1"), "age" : 30 }
> db.students.find({age:{$in:}})
{ "_id" : ObjectId("58d50e6376002e9a38ccceec"), "name" : "tom", "age" : 23 }
{ "_id" : ObjectId("58d51cec76002e9a38ccceef"), "name" : "x1", "age" : 40 }
> db.students.find({age:{$nin:}})
{ "_id" : ObjectId("58d5183976002e9a38ccceed"), "name" : "xj" }
{ "_id" : ObjectId("58d51b2776002e9a38ccceee"), "name" : "xx", "Age" : 35 }
{ "_id" : ObjectId("58d51cff76002e9a38cccef0"), "name" : "x2", "age" : 50 }
{ "_id" : ObjectId("58d51f0e76002e9a38cccef1"), "age" : 30 }
组合条件:逻辑运算
$or:或运算
$and:与运算
$nor:反运算,返回不符合指定条件的所有文档
语法格式:
{$or:[{},...]}
最少条件2个子句
$not:非运算
只有$not格式和上面的不一样
执行逻辑NOT运算,选择出不能匹配表达式的文档 ,包括没有指定键的文档。$not操作符不能独立使用,必须跟其他操作一起使用(除$regex)。
{field:{$not:}}}
> db.students.find({$or:[{age:{$gt:30}},{Age:{$gt:30}}]})
{ "_id" : ObjectId("58d51b2776002e9a38ccceee"), "name" : "xx", "Age" : 35 }
{ "_id" : ObjectId("58d51cec76002e9a38ccceef"), "name" : "x1", "age" : 40 }
{ "_id" : ObjectId("58d51cff76002e9a38cccef0"), "name" : "x2", "age" : 50 }
> db.students.find({$nor:[{age:{$gt:30}}]})
{ "_id" : ObjectId("58d50e6376002e9a38ccceec"), "name" : "tom", "age" : 23 }
{ "_id" : ObjectId("58d5183976002e9a38ccceed"), "name" : "xj" }
{ "_id" : ObjectId("58d51b2776002e9a38ccceee"), "name" : "xx", "Age" : 35 }
{ "_id" : ObjectId("58d51f0e76002e9a38cccef1"), "age" : 30 }
> db.students.find({age:{$not:{$gt:30}}})
{ "_id" : ObjectId("58d50e6376002e9a38ccceec"), "name" : "tom", "age" : 23 }
{ "_id" : ObjectId("58d5183976002e9a38ccceed"), "name" : "xj" }
{ "_id" : ObjectId("58d51b2776002e9a38ccceee"), "name" : "xx", "Age" : 35 }
{ "_id" : ObjectId("58d51f0e76002e9a38cccef1"), "age" : 30 }
元素查询
根据文档中是否存在指定的字段进行的查询
$exists:
语法格式:
{filed:{$exists:}}
> db.students.find()
{ "_id" : ObjectId("58d50e6376002e9a38ccceec"), "name" : "tom", "age" : 23 }
{ "_id" : ObjectId("58d5183976002e9a38ccceed"), "name" : "xj" }
{ "_id" : ObjectId("58d51b2776002e9a38ccceee"), "name" : "xx", "Age" : 35 }
{ "_id" : ObjectId("58d51cec76002e9a38ccceef"), "name" : "x1", "age" : 40 }
{ "_id" : ObjectId("58d51cff76002e9a38cccef0"), "name" : "x2", "age" : 50 }
{ "_id" : ObjectId("58d51f0e76002e9a38cccef1"), "age" : 30 }
{ "_id" : ObjectId("58d5261d76002e9a38cccef2"), "age" : "" }
{ "_id" : ObjectId("58d5262a76002e9a38cccef3"), "age" : "null" }
{ "_id" : ObjectId("58d5264576002e9a38cccef4"), "age" : "Null" }
{ "_id" : ObjectId("58d5271f76002e9a38cccef5"), "age" : null }
{ "_id" : ObjectId("58d5274b76002e9a38cccef6"), "age" : " " }
{ "_id" : ObjectId("58d527c176002e9a38cccef7"), "age" : null }
> db.students.find({name: {$exists:true}})
{ "_id" : ObjectId("58d50e6376002e9a38ccceec"), "name" : "tom", "age" : 23 }
{ "_id" : ObjectId("58d5183976002e9a38ccceed"), "name" : "xj" }
{ "_id" : ObjectId("58d51b2776002e9a38ccceee"), "name" : "xx", "Age" : 35 }
{ "_id" : ObjectId("58d51cec76002e9a38ccceef"), "name" : "x1", "age" : 40 }
{ "_id" : ObjectId("58d51cff76002e9a38cccef0"), "name" : "x2", "age" : 50 }
> db.students.find({name: {$exists:false}})
{ "_id" : ObjectId("58d51f0e76002e9a38cccef1"), "age" : 30 }
{ "_id" : ObjectId("58d5261d76002e9a38cccef2"), "age" : "" }
{ "_id" : ObjectId("58d5262a76002e9a38cccef3"), "age" : "null" }
{ "_id" : ObjectId("58d5264576002e9a38cccef4"), "age" : "Null" }
{ "_id" : ObjectId("58d5271f76002e9a38cccef5"), "age" : null }
{ "_id" : ObjectId("58d5274b76002e9a38cccef6"), "age" : " " }
{ "_id" : ObjectId("58d527c176002e9a38cccef7"), "age" : null }
键值为null查询操作
如何检索出age键值为null的文档,"$in"判断键值是否为null,"$exists"判定集合中文档是否包含该键。
> db.students.find()
{ "_id" : ObjectId("58d50e6376002e9a38ccceec"), "name" : "tom", "age" : 23 }
{ "_id" : ObjectId("58d5183976002e9a38ccceed"), "name" : "xj" }
{ "_id" : ObjectId("58d51b2776002e9a38ccceee"), "name" : "xx", "Age" : 35 }
{ "_id" : ObjectId("58d51cec76002e9a38ccceef"), "name" : "x1", "age" : 40 }
{ "_id" : ObjectId("58d51cff76002e9a38cccef0"), "name" : "x2", "age" : 50 }
{ "_id" : ObjectId("58d51f0e76002e9a38cccef1"), "age" : 30 }
{ "_id" : ObjectId("58d5261d76002e9a38cccef2"), "age" : "" }
{ "_id" : ObjectId("58d5262a76002e9a38cccef3"), "age" : "null" }
{ "_id" : ObjectId("58d5264576002e9a38cccef4"), "age" : "Null" }
{ "_id" : ObjectId("58d5271f76002e9a38cccef5"), "age" : null }
{ "_id" : ObjectId("58d5274b76002e9a38cccef6"), "age" : " " }
> db.students.find({age:{$in:,$exists:true}})
{ "_id" : ObjectId("58d5271f76002e9a38cccef5"), "age" : null }
> db.students.find({age:null}) # 这样查包含了不喊age字段的文档
{ "_id" : ObjectId("58d5183976002e9a38ccceed"), "name" : "xj" }
{ "_id" : ObjectId("58d51b2776002e9a38ccceee"), "name" : "xx", "Age" : 35 }
{ "_id" : ObjectId("58d5271f76002e9a38cccef5"), "age" : null }
以下的用的不多:
$mod:将指定元素做取模运算,并返回指定余数的文档
$type:返回指定字段的值的类型为指定类型的文档
语法格式:
{filed:{$type:}}
type:用数字标识
1:Doble
2:String
3:Object
Array,Binary data,Undefined,Boolean,Date
3、更新文档
MongoDB 使用 update()方法来更新集合中的文档。
db.mycoll.update() 方法用于更新已存在的文档。
> db.students.find({name:"tom"})
{ "_id" : ObjectId("58d50e6376002e9a38ccceec"), "name" : "tom", "age" : 20 }
> db.students.update({name:"tom"},{$set: {age:25}})
> db.students.find({name:"tom"})
{ "_id" : ObjectId("58d50e6376002e9a38ccceec"), "name" : "tom", "age" : 25 }
> db.students.update({name:"tom"},{$set: {name:"toms"}})
> db.students.find({name:"toms"})
{ "_id" : ObjectId("58d50e6376002e9a38ccceec"), "age" : 25, "name" : "toms" }
$set:修改过字段的值为新指定的值,语法格式:
{filed: value},{$set:{filed: new_value}}
$unset:删除指定字段,语法格式
{filed:value},{$unset:{filed1,filed2,...}}
$inc:增加
4、删除操作
删除文档
db.mycoll.remove()函数是用来移除集合中的数据。
语法格式:
db.collection.remove( ,
)
参数说明:
query:(可选)删除的文档的条件。
justOne: (可选)如果设为 true 或 1
writeConcern:(可选)抛出异常的级别。
如果什么参数都不带,则默认删除所有的文档
> db.students.find({name:"toms"})
{ "_id" : ObjectId("58d50e6376002e9a38ccceec"), "age" : 25, "name" : "toms" }
> db.students.remove({name:"toms"})
> db.students.find({name:"toms"})
删除collection
db.mycoll.droup()
> show collections
ay
students
system.indexes
> db.ay.drop()
true
> show collections
students
system.indexes
>
删除数据库
db.dropDatabase() # 删除当前数据库
> db
testdb
> show dbs
local0.078125GB
sb(empty)
students0.203125GB
test(empty)
testdb0.203125GB
> db.dropDatabase()
{ "dropped" : "testdb", "ok" : 1 }
> show dbs
local0.078125GB
sb(empty)
students0.203125GB
test(empty)
页:
[1]