CentOS7 安装MongoDB和实操

CentOS7 安装MongoDB

  1. 准备包:
    方式1)下载官网地址:https://www.mongodb.com/download-center/community
    方式2)如果可以联网,也可以通过wget来下载
    wget https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-rhel70-3.2.4.tgz

2.解压和配置
[root@fang opt]# mkdir -p /usr/local/mongodb
[root@fang opt]# tar -zxvf mongodb-linux-x86_64-rhel70-3.2.4.tgz -C /usr/local/mongodb
[root@fang mongodb]# mv mongodb-linux-x86_64-rhel70-3.2.4/ mongodb3.2.4
[root@fang mongodb3.2.4]# mkdir -p data/test/logs
[root@fang mongodb3.2.4]# mkdir -p data/test/db

3.创建配置文件
vi mongodb.conf
[root@fang bin]# more mongodb.conf

设置数据文件的存放目录

dbpath = /usr/local/mongodb/mongodb3.2.4/data/test/db

设置日志文件的存放目录及其日志文件名

logpath = /usr/local/mongodb/mongodb3.2.4/data/test/logs/mongodb.log

设置端口号(默认的端口号是 27017)

port = 27017

设置为以守护进程的方式运行,即在后台运行

fork = true
nohttpinterface = true
[root@fang bin]#

参数解释:
–dbpath 数据库路径(数据文件)
–logpath 日志文件路径
–master 指定为主机器
–slave 指定为从机器
–source 指定主机器的IP地址
–pologSize 指定日志文件大小不超过64M.因为resync是非常操作量大且耗时,最好通过设置一个足够大的oplogSize来避免resync(默认的 oplog大小是空闲磁盘大小的5%)。
–logappend 日志文件末尾添加,即使用追加的方式写日志
–journal 启用日志
–port 启用端口号
–fork 在后台运行
–only 指定只复制哪一个数据库
–slavedelay 指从复制检测的时间间隔
–auth 是否需要验证权限登录(用户名和密码)
–syncdelay 数据写入硬盘的时间(秒),0是不等待,直接写入
–notablescan 不允许表扫描
–maxConns 最大的并发连接数,默认2000
–pidfilepath 指定进程文件,不指定则不产生进程文件
–bind_ip 绑定IP,绑定后只能绑定的IP访问服务

3.环境变量配置

  1. 启动常见命令
    1)启动
    mongod --config $MONGO/bin/mongodb.conf
    mongod --repair -f $MONGO/bin/mongodb.conf
    2)查看进程和日志等
    ps aux | grep mongodb
    more mongodb.log
    netstat -lanp | grep 27017
    ps aux | grep mongodb
    tail -200f /usr/local/mongodb/mongodb3.2.4/data/test/logs/mongodb.log
    ps -efaux | grep 1510

  2. mongo命令
    [root@fang ~]# mongo
    MongoDB shell version: 3.2.4
    connecting to: 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
    Server has startup warnings:
    2019-05-07T14:41:19.423+0800 I CONTROL [initandlisten] ** WARNING: You are running this process as the root user, which is not recommended.
    2019-05-07T14:41:19.423+0800 I CONTROL [initandlisten]
    2019-05-07T14:41:19.423+0800 I CONTROL [initandlisten]
    2019-05-07T14:41:19.423+0800 I CONTROL [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is ‘always’.
    2019-05-07T14:41:19.423+0800 I CONTROL [initandlisten] ** We suggest setting it to ‘never’
    2019-05-07T14:41:19.423+0800 I CONTROL [initandlisten]
    2019-05-07T14:41:19.423+0800 I CONTROL [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/defrag is ‘always’.
    2019-05-07T14:41:19.423+0800 I CONTROL [initandlisten] ** We suggest setting it to ‘never’
    2019-05-07T14:41:19.423+0800 I CONTROL [initandlisten]

help
db.stats()
{
“db” : “test”,
“collections” : 0,
“objects” : 0,
“avgObjSize” : 0,
“dataSize” : 0,
“storageSize” : 0,
“numExtents” : 0,
“indexes” : 0,
“indexSize” : 0,
“fileSize” : 0,
“ok” : 1
}
2+2
4
3+6
9
db.version()
3.2.4
db.runoob.insert
db.runoob.insert( db.runoob.insertMany( db.runoob.insertOne(
db.runoob.insert({x:10})
WriteResult({ “nInserted” : 1 })
db.runoob.find()
{ “_id” : ObjectId(“5cd12b1e20fee774e0cc1fcf”), “x” : 10 }
show dbs
local 0.000GB
test 0.000GB
db
test
user local
2019-05-07T14:56:25.996+0800 E QUERY [thread1] SyntaxError: missing ; before statement @(shell):1:5

db
test
use local
switched to db local
db
local
use test
switched to db test
db
test

MongoDB 数据类型

数据类型 描述
String 字符串。存储数据常用的数据类型。在 MongoDB 中,UTF-8 编码的字符串才是合法的。
Integer 整型数值。用于存储数值。根据你所采用的服务器,可分为 32 位或 64 位。
Boolean 布尔值。用于存储布尔值(真/假)。
Double 双精度浮点值。用于存储浮点值。
Min/Max keys 将一个值与 BSON(二进制的 JSON)元素的最低值和最高值相对比。
Array 用于将数组或列表或多个值存储为一个键。
Timestamp 时间戳。记录文档修改或添加的具体时间。
Object 用于内嵌文档。
Null 用于创建空值。
Symbol 符号。该数据类型基本上等同于字符串类型,但不同的是,它一般用于采用特殊符号类型的语言。
Date 日期时间。用 UNIX 时间格式来存储当前日期或时间。你可以指定自己的日期时间:创建 Date 对象,传入年月日信息。
Object ID 对象 ID。用于创建文档的 ID。
Binary Data 二进制数据。用于存储二进制数据。
Code 代码类型。用于在文档中存储 JavaScript 代码。
Regular expression 正则表达式类型。用于存储正则表达式。

ObjectId
ObjectId 类似唯一主键,可以很快的去生成和排序,包含 12 bytes,含义是:
• 前 4 个字节表示创建 unix 时间戳,格林尼治时间 UTC 时间,比北京时间晚了 8 个小时
• 接下来的 3 个字节是机器标识码
• 紧接的两个字节由进程 id 组成 PID
• 最后三个字节是随机数

MongoDB 中存储的文档必须有一个 _id 键。这个键的值可以是任何类型的,默认是个 ObjectId 对象
由于 ObjectId 中保存了创建的时间戳,所以你不需要为你的文档保存时间戳字段,你可以通过 getTimestamp 函数来获取文档的创建时间:
MONGODB区分大小写,所以函数千万不要写错,否则就报错

var newobject = ObjectId()
newobject.getTimestamp()
ISODate(“2019-05-07T07:04:55Z”)

ObjectId 转为字符串

newobject.str
5cd12e1720fee774e0cc1fd0

日期操作:

var mydate1 = new Date()
mydate1
ISODate(“2019-05-07T07:09:29.517Z”)
var mydate1str = mydate1.toString(
Display all 177 possibilities? (y or n)
var mydate1str = mydate1.toString()
mydate1str
Tue May 07 2019 15:09:29 GMT+0800 (CST)
Date()
Tue May 07 2019 15:10:13 GMT+0800 (CST)
typeof mydate1
object
typeof mydate1str
string

–插入:
collection:表
比如下面的mycol,col,runoob都是表
document为一行记录

use test
switched to db test
db
test
show collections
mycol
runoob
db.mycol.find()
db.runoob.find()
{ “_id” : ObjectId(“5cd12b1e20fee774e0cc1fcf”), “x” : 10 }
db.mycol.drop() 删除集合
true
show collections
runoob
db.col.insert( {title:‘test’,
… description: ‘MongoDB is a nosql database’,
… by: ‘cainiaojiaocheng’,
… url: ‘http://www.runnoob.com’,
… tags: [‘mongodb’,‘database’,‘NoSql’],
… likes:100 })
WriteResult({ “nInserted” : 1 })
db.col.find()
{ “_id” : ObjectId(“5cd132b3bb90bcd4b85f95a1”), “title” : “test”, “description” : “MongoDB is a nosql database”, “by” : “cainiaojiaocheng”, “url” : “http://www.runnoob.com”, “tags” : [ “mongodb”, “database”, “NoSql” ], “likes” : 100 }

document=({title:‘test’, description: ‘MongoDB is a nosql database’, by: ‘cainiaojiaocheng’, url: ‘http://www.runnoob.com’, tags: [‘mongodb’,‘database’,‘NoSql’], likes:100 })
{
“title” : “test”,
“description” : “MongoDB is a nosql database”,
“by” : “cainiaojiaocheng”,
“url” : “http://www.runnoob.com”,
“tags” : [
“mongodb”,
“database”,
“NoSql”
],
“likes” : 100
}
db.col.insert(document)
WriteResult({ “nInserted” : 1 })
db.col.save(document)
WriteResult({ “nInserted” : 1 })
db.col.find().pretty()
{
“_id” : ObjectId(“5cd132b3bb90bcd4b85f95a1”),
“title” : “test”,
“description” : “MongoDB is a nosql database”,
“by” : “cainiaojiaocheng”,
“url” : “http://www.runnoob.com”,
“tags” : [
“mongodb”,
“database”,
“NoSql”
],
“likes” : 100
}

–删除:

db.col.remove({}) --删除所有 remove后不会释放空间,需要> db.repairDatabase()

WriteResult({ “nRemoved” : 3 })

db.col.find()
db.[collectionName].remove({key:value})
根据条件删除:
db.sample.remove({name:“c”})
如果collect很大,最快全部清除就是删除collect然后重新创建。

db.test.deleteMany({“name”:“fw”})
{ “acknowledged” : true, “deletedCount” : 1 }
db.test.find()
{ “_id” : ObjectId(“5cd13dc8bb90bcd4b85f95a9”), “name” : “fangwei”, “language” : [ “python”, “Scala” ], “email” : “test@qq.com” }

db.test.deleteOne({“name”:“fw”}) --删除一个

–更新:
db.[collectionName].update({查询器},{修改器},true)
第三个参数设置为true,代表insertOrUpdate,即存在即更新,否则插入该数据 ,默认为false

db.col.find()
{ “_id” : ObjectId(“5cd135ebbb90bcd4b85f95a4”), “name” : “fangwei” }
{ “_id” : ObjectId(“5cd13650bb90bcd4b85f95a5”), “name” : “fangwei”, “age” : 15 }
db.col.update({“name”:“fangwei”},{“name”:“FW”})
WriteResult({ “nMatched” : 1, “nUpserted” : 0, “nModified” : 1 })
db.col.find()
{ “_id” : ObjectId(“5cd135ebbb90bcd4b85f95a4”), “name” : “FW” }
{ “_id” : ObjectId(“5cd13650bb90bcd4b85f95a5”), “name” : “fangwei”, “age” : 15 }

MongoDB默认匹配多条时,只会更新第一条。

db.[collectionName].update({查询器},{修改器},false, true)
第四个参数就是全量更新

db.col.insert({‘name’:‘fangwei’})
WriteResult({ “nInserted” : 1 })
db.col.find()
{ “_id” : ObjectId(“5cd135ebbb90bcd4b85f95a4”), “name” : “FW” }
{ “_id” : ObjectId(“5cd13650bb90bcd4b85f95a5”), “name” : “fangwei”, “age” : 15 }
{ “_id” : ObjectId(“5cd137d8bb90bcd4b85f95a6”), “name” : “fangwei” }
{ “_id” : ObjectId(“5cd137dfbb90bcd4b85f95a7”), “name” : “fangwei” }

db.col.update({“name”:“fangwei”},{$set:{“name”:“FW”}},false,true)
WriteResult({ “nMatched” : 3, “nUpserted” : 0, “nModified” : 3 })

db.col.find().pretty()
{ “_id” : ObjectId(“5cd135ebbb90bcd4b85f95a4”), “name” : “FW” }
{ “_id” : ObjectId(“5cd13650bb90bcd4b85f95a5”), “name” : “FW”, “age” : 15 }
{ “_id” : ObjectId(“5cd137d8bb90bcd4b85f95a6”), “name” : “FW” }
{ “_id” : ObjectId(“5cd137dfbb90bcd4b85f95a7”), “name” : “FW” }

set修改器,根据key来映射修改,如果匹配上就修改
db.col.update({“name”:“FW”},{$set:{“name”:“fangwei”}})

db.col.find().pretty()
{ “_id” : ObjectId(“5cd135ebbb90bcd4b85f95a4”), “name” : “FW” }
{ “_id” : ObjectId(“5cd13650bb90bcd4b85f95a5”), “name” : “FW”, “age” : 15 }
{ “_id” : ObjectId(“5cd137d8bb90bcd4b85f95a6”), “name” : “FW” }
{ “_id” : ObjectId(“5cd137dfbb90bcd4b85f95a7”), “name” : “FW” }
db.col.update({“name”:“FW”},{KaTeX parse error: Expected 'EOF', got '}' at position 23: …ame":"fangwei"}}̲) WriteResult({…set:{“name”:“fangwei”}},false,true)
unset修改器unset修改器用法很简单,就是删除指定的键值对
{ $unset: { field : 1} }
example: { KaTeX parse error: Expected 'EOF', got '}' at position 23: … { "age" : 1 } }̲ db.col.update(…unset:{age:1}})
WriteResult({ “nMatched” : 1, “nUpserted” : 0, “nModified” : 1 })
db.col.find().pretty()
{ “_id” : ObjectId(“5cd135ebbb90bcd4b85f95a4”), “name” : “fangwei” }
{ “_id” : ObjectId(“5cd13650bb90bcd4b85f95a5”), “name” : “fangwei” }
{ “_id” : ObjectId(“5cd137d8bb90bcd4b85f95a6”), “name” : “fangwei” }
{ “_id” : ObjectId(“5cd137dfbb90bcd4b85f95a7”), “name” : “fangwei” }

push修改器 对应$pull修改器(删除数组数据) $addToSet(不添加重复数据)

db.test.find()
{ “_id” : ObjectId(“5cd13dc8bb90bcd4b85f95a9”), “name” : “fangwei”, “language” : [ “java”, “C++”, “python” ] }
db.test.update({name:“fangwei”},{$push:{“language”:“Scala”}})
WriteResult({ “nMatched” : 1, “nUpserted” : 0, “nModified” : 1 })
db.test.find()
{ “_id” : ObjectId(“5cd13dc8bb90bcd4b85f95a9”), “name” : “fangwei”, “language” : [ “java”, “C++”, “python”, “Scala” ] }
$pushAll修改器
p u s h A l l 修 改 器 用 法 和 pushAll修改器用法和 pushAllpush相似他可以批量添加数组数据
即可以添加整个数组,如下:

// 修改器名称:$pushAll 对应 $pullAll修改器(删除数组数据)
// 语法:{ KaTeX parse error: Expected 'EOF', got '}' at position 28: …field : array} }̲ db.test.update…pushAll:{“language”:[“perl”,“C#”]}})

db.test.find()
{ “_id” : ObjectId(“5cd13dc8bb90bcd4b85f95a9”), “name” : “fangwei”, “language” : [ “java”, “C++”, “python”, “Scala”, “perl”, “C#” ] }

db.test.update({“name”:“fangwei”},{$pushAll:{“language”:[“perl”,“C#”]}})
WriteResult({ “nMatched” : 1, “nUpserted” : 0, “nModified” : 1 })
db.test.find()
{ “_id” : ObjectId(“5cd13dc8bb90bcd4b85f95a9”), “name” : “fangwei”, “language” : [ “java”, “C++”, “python”, “Scala”, “perl”, “C#”, “perl”, “C#” ] }

$pop 删除 >=0删除最后一个, <0 删除第一个

db.test.find()
{ “_id” : ObjectId(“5cd13dc8bb90bcd4b85f95a9”), “name” : “fangwei”, “language” : [ “java”, “C++”, “python”, “Scala”, “perl”, “C#”, “perl” ] }
db.test.update({“name”:“fangwei”},{$pop:{“language”:1}})
WriteResult({ “nMatched” : 1, “nUpserted” : 0, “nModified” : 1 })
db.test.find()
{ “_id” : ObjectId(“5cd13dc8bb90bcd4b85f95a9”), “name” : “fangwei”, “language” : [ “java”, “C++”, “python”, “Scala”, “perl”, “C#” ] }

db.test.update({“name”:“fangwei”},{$pop:{“language”:-1}})
WriteResult({ “nMatched” : 1, “nUpserted” : 0, “nModified” : 1 })
db.test.find()
{ “_id” : ObjectId(“5cd13dc8bb90bcd4b85f95a9”), “name” : “fangwei”, “language” : [ “C++”, “python”, “Scala”, “perl”, “C#” ] }

数 组 定 位 符 1. 数组定位符 1. 1.数组定位器,如果数组有多个数值我们只想对其中一部分进行操作我们就要用到定位器($)

// 修改器名称:$
// 语法:{ KaTeX parse error: Expected '}', got 'EOF' at end of input: set: { array..field : value} }
// example:
{ KaTeX parse error: Expected '}', got 'EOF' at end of input: …et: { database..com : “sun”}
例如有文档:
{ “_id” : ObjectId(“5656d2876cc2cfd9ab5373b7”), “name” : “evers”, “age” : 25, “database” : [ { “type” : “Oracle”, “name” : “OracleDB” }, { “type” : “MySQL”, “name” : “MySQLDB” }, { “type” : “MongoDB”, “name” : “MongoDBDB” } ] }

我们要把type等于MongoDB的文档增加一个作者author是Mongo
办法:

db.sample.update({“database.type”:“MongoDB”},{KaTeX parse error: Expected '}', got 'EOF' at end of input: set:{"database..author":“Mongo”}})

runCommand可以执行mongoDB中的特殊函数,findAndModify就是特殊函数之一,他的作用是返回update或remove后的文档

runCommand({“findAndModify”:“processes”,
query:{查询器},
sort{排序},
new:true
update:{更新器},
remove:true
}).value
// example:

ps = db.runCommand({
… “findAndModify”:“test”,
… “query”:{“name”:“fangwei”},
… “update”:{$set:{“email”:“test@qq.com”}},
… “new”:true
… }).value
{
“_id” : ObjectId(“5cd13dc8bb90bcd4b85f95a9”),
“name” : “fangwei”,
“language” : [
“python”,
“Scala”
],
“email” : “test@qq.com”
}
db.test.find()
{ “_id” : ObjectId(“5cd13dc8bb90bcd4b85f95a9”), “name” : “fangwei”, “language” : [ “python”, “Scala” ], “email” : “test@qq.com” }
{ “_id” : ObjectId(“5cd14343bb90bcd4b85f95aa”), “name” : “fw”, “email” : “12321321@qq.com” }

查询
MongoDB 与 RDBMS Where 语句比较
如果你熟悉常规的 SQL 数据,通过下表可以更好的理解 MongoDB 的条件语句查询:
操作 格式 范例 RDBMS中的类似语句
等于 {:} db.col.find({“by”:“菜鸟教程”}).pretty() where by = ‘菜鸟教程’
小于 {:{KaTeX parse error: Expected 'EOF', got '}' at position 11: lt:<value>}̲} db.col.find({…lt:50}}).pretty() where likes < 50
小于或等于 {:{KaTeX parse error: Expected 'EOF', got '}' at position 12: lte:<value>}̲} db.col.find({…lte:50}}).pretty() where likes <= 50
大于 {:{KaTeX parse error: Expected 'EOF', got '}' at position 11: gt:<value>}̲} db.col.find({…gt:50}}).pretty() where likes > 50
大于或等于 {:{KaTeX parse error: Expected 'EOF', got '}' at position 12: gte:<value>}̲} db.col.find({…gte:50}}).pretty() where likes >= 50
不等于 {:{KaTeX parse error: Expected 'EOF', got '}' at position 11: ne:<value>}̲} db.col.find({…ne:50}}).pretty() where likes != 50


MongoDB AND 条件
MongoDB 的 find() 方法可以传入多个键(key),每个键(key)以逗号隔开,即常规 SQL 的 AND 条件。
语法格式如下:

db.col.find({key1:value1, key2:value2}).pretty()
准备数据:

db.t.insert({“id”:1,“name”:“a”,“age”:20})
db.t.insert({“id”:2,“name”:“b”,“age”:14})
db.t.insert({“id”:3,“name”:“c”,“age”:23})
db.t.insert({“id”:4,“name”:“d”,“age”:40})
db.t.insert({“id”:5,“name”:“e”,“age”:50})
db.t.insert({“id”:6,“name”:“f”,“age”:33})

db.t.find()
{ “_id” : ObjectId(“5cd14f49bb90bcd4b85f95ab”), “id” : 1, “name” : “a”, “age” : 20 }
{ “_id” : ObjectId(“5cd14f67bb90bcd4b85f95ac”), “id” : 2, “name” : “b”, “age” : 14 }
{ “_id” : ObjectId(“5cd14f67bb90bcd4b85f95ad”), “id” : 3, “name” : “c”, “age” : 23 }
{ “_id” : ObjectId(“5cd14f67bb90bcd4b85f95ae”), “id” : 4, “name” : “d”, “age” : 40 }
{ “_id” : ObjectId(“5cd14f67bb90bcd4b85f95af”), “id” : 5, “name” : “e”, “age” : 50 }
{ “_id” : ObjectId(“5cd14f68bb90bcd4b85f95b0”), “id” : 6, “name” : “f”, “age” : 33 }

db.t.find({“id”:1})
{ “_id” : ObjectId(“5cd14f49bb90bcd4b85f95ab”), “id” : 1, “name” : “a”, “age” : 20 }
db.t.find({“id”:1},{“id”:1,“name”:1})
{ “_id” : ObjectId(“5cd14f49bb90bcd4b85f95ab”), “id” : 1, “name” : “a” }
db.t.find({“id”:1,“name”:“a”})
{ “_id” : ObjectId(“5cd14f49bb90bcd4b85f95ab”), “id” : 1, “name” : “a”, “age” : 20 }
db.t.find({‘KaTeX parse error: Expected 'EOF', got '}' at position 24: …d':1},{'id':2}]}̲) { "_id" : Obj…gte’:10,’$lte’:30}}) 10<=age<=30
{ “_id” : ObjectId(“5cd14f49bb90bcd4b85f95ab”), “id” : 1, “name” : “a”, “age” : 20 }
{ “_id” : ObjectId(“5cd14f67bb90bcd4b85f95ac”), “id” : 2, “name” : “b”, “age” : 14 }
{ “_id” : ObjectId(“5cd14f67bb90bcd4b85f95ad”), “id” : 3, “name” : “c”, “age” : 23 }

db.t.find({‘age’:null})
db.t.find({‘id’:{‘KaTeX parse error: Expected 'EOF', got '}' at position 12: in':[1,2,5]}̲}) { "_id" : Ob…nin’:[1,2,5]}})
{ “_id” : ObjectId(“5cd14f67bb90bcd4b85f95ad”), “id” : 3, “name” : “c”, “age” : 23 }
{ “_id” : ObjectId(“5cd14f67bb90bcd4b85f95ae”), “id” : 4, “name” : “d”, “age” : 40 }
{ “_id” : ObjectId(“5cd14f68bb90bcd4b85f95b0”), “id” : 6, “name” : “f”, “age” : 33 }

like “%f%”
db.t.insert({“id”:6,“name”:“f1”,“age”:33})
db.t.insert({“id”:6,“name”:“1f1”,“age”:33})
db.t.insert({“id”:6,“name”:“1f”,“age”:33})
db.t.insert({“id”:6,“name”:“1ff1”,“age”:33})
db.t.insert({“id”:6,“name”:“1111ff1111”,“age”:33})

db.t.find({name:/f/})
{ “_id” : ObjectId(“5cd14f68bb90bcd4b85f95b0”), “id” : 6, “name” : “f”, “age” : 33 }
{ “_id” : ObjectId(“5cd1524abb90bcd4b85f95b2”), “id” : 6, “name” : “1f1”, “age” : 33 }
{ “_id” : ObjectId(“5cd152a0bb90bcd4b85f95b3”), “id” : 6, “name” : “f1”, “age” : 33 }
{ “_id” : ObjectId(“5cd152ecbb90bcd4b85f95b4”), “id” : 6, “name” : “1f”, “age” : 33 }

db.t.find({name:/^f/})
{ “_id” : ObjectId(“5cd14f68bb90bcd4b85f95b0”), “id” : 6, “name” : “f”, “age” : 33 }
{ “_id” : ObjectId(“5cd152a0bb90bcd4b85f95b3”), “id” : 6, “name” : “f1”, “age” : 33 }
db.t.find({name:/f$/})
{ “_id” : ObjectId(“5cd14f68bb90bcd4b85f95b0”), “id” : 6, “name” : “f”, “age” : 33 }
{ “_id” : ObjectId(“5cd152ecbb90bcd4b85f95b4”), “id” : 6, “name” : “1f”, “age” : 33 }

db.t.find({name:/1(.f.[^f])/})
{ “_id” : ObjectId(“5cd1524abb90bcd4b85f95b2”), “id” : 6, “name” : “1f1”, “age” : 33 }
{ “_id” : ObjectId(“5cd15726bb90bcd4b85f95b5”), “id” : 6, “name” : “1ff1”, “age” : 33 }
{ “_id” : ObjectId(“5cd15745bb90bcd4b85f95b6”), “id” : 6, “name” : “1111ff1111”, “age” : 33 }
db.t.distinct(‘name’)
[
“a”,
“b”,
“c”,
“d”,
“e”,
“f”,
“1f1”,
“f1”,
“1f”,
“1ff1”,
“1111ff1111”
]
db.t.distinct(‘age’)
[ 20, 14, 23, 40, 50, 33 ]
db.t.find()
{ “_id” : ObjectId(“5cd14f49bb90bcd4b85f95ab”), “id” : 1, “name” : “a”, “age” : 20 }
{ “_id” : ObjectId(“5cd14f67bb90bcd4b85f95ac”), “id” : 2, “name” : “b”, “age” : 14 }
{ “_id” : ObjectId(“5cd14f67bb90bcd4b85f95ad”), “id” : 3, “name” : “c”, “age” : 23 }
{ “_id” : ObjectId(“5cd14f67bb90bcd4b85f95ae”), “id” : 4, “name” : “d”, “age” : 40 }
{ “_id” : ObjectId(“5cd14f67bb90bcd4b85f95af”), “id” : 5, “name” : “e”, “age” : 50 }
{ “_id” : ObjectId(“5cd14f68bb90bcd4b85f95b0”), “id” : 6, “name” : “f”, “age” : 33 }
{ “_id” : ObjectId(“5cd1524abb90bcd4b85f95b2”), “id” : 6, “name” : “1f1”, “age” : 33 }
{ “_id” : ObjectId(“5cd152a0bb90bcd4b85f95b3”), “id” : 6, “name” : “f1”, “age” : 33 }
{ “_id” : ObjectId(“5cd152ecbb90bcd4b85f95b4”), “id” : 6, “name” : “1f”, “age” : 33 }
{ “_id” : ObjectId(“5cd15726bb90bcd4b85f95b5”), “id” : 6, “name” : “1ff1”, “age” : 33 }
{ “_id” : ObjectId(“5cd15745bb90bcd4b85f95b6”), “id” : 6, “name” : “1111ff1111”, “age” : 33 }
db.t.distinct(‘id’)
[ 1, 2, 3, 4, 5, 6 ]
db.t.count()
11

强大的$where查询

db.foo.insert({“a”:1,“b”:3,“c”:10})
WriteResult({ “nInserted” : 1 })
db.foo.insert({“a”:1,“b”:6,“c”:6})
WriteResult({ “nInserted” : 1 })
db.foo.find()
{ “_id” : ObjectId(“5cd15a25bb90bcd4b85f95b7”), “a” : 1, “b” : 3, “c” : 10 }
{ “_id” : ObjectId(“5cd15a2cbb90bcd4b85f95b8”), “a” : 1, “b” : 6, “c” : 6 }

如果要查询 b = c 的文档怎么办?

db.foo.find({"$where":function(){
for(var current in this){
for(var other in this){
if(current != other && this[current] == this[other]){
return true;
}
}
}
return false;
}});
{ “_id” : ObjectId(“5cd15a2cbb90bcd4b85f95b8”), “a” : 1, “b” : 6, “c” : 6 }

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

db.foo.find({“a”:{KaTeX parse error: Expected 'EOF', got '}' at position 7: type:1}̲}) { "_id" : Ob…type:‘double’}})
{ “_id” : ObjectId(“5cd15a25bb90bcd4b85f95b7”), “a” : 1, “b” : 3, “c” : 10 }
{ “_id” : ObjectId(“5cd15a2cbb90bcd4b85f95b8”), “a” : 1, “b” : 6, “c” : 6 }

db.t.find({“name”:{KaTeX parse error: Expected 'EOF', got '}' at position 14: type:'string'}̲}) { "_id" : Ob…type:2}})
{ “_id” : ObjectId(“5cd14f49bb90bcd4b85f95ab”), “id” : 1, “name” : “a”, “age” : 20 }
{ “_id” : ObjectId(“5cd14f67bb90bcd4b85f95ac”), “id” : 2, “name” : “b”, “age” : 14 }

db.t.find({“name”:{KaTeX parse error: Expected 'EOF', got '}' at position 7: type:2}̲}).limit(1) { "…type:2}}).limit(3)
{ “_id” : ObjectId(“5cd14f49bb90bcd4b85f95ab”), “id” : 1, “name” : “a”, “age” : 20 }
{ “_id” : ObjectId(“5cd14f67bb90bcd4b85f95ac”), “id” : 2, “name” : “b”, “age” : 14 }
{ “_id” : ObjectId(“5cd14f67bb90bcd4b85f95ad”), “id” : 3, “name” : “c”, “age” : 23 }

db.t.find({“name”:{$type:2}}).limit(3).skip(1)
{ “_id” : ObjectId(“5cd14f67bb90bcd4b85f95ac”), “id” : 2, “name” : “b”, “age” : 14 }
{ “_id” : ObjectId(“5cd14f67bb90bcd4b85f95ad”), “id” : 3, “name” : “c”, “age” : 23 }
{ “_id” : ObjectId(“5cd14f67bb90bcd4b85f95ae”), “id” : 4, “name” : “d”, “age” : 40 }

在 MongoDB 中使用 sort() 方法对数据进行排序,sort() 方法可以通过参数指定排序的字段,并使用 1 和 -1 来指定排序的方式,其中 1 为升序排列,而 -1 是用于降序排列。

db.t.find().sort({“name”:1})
{ “_id” : ObjectId(“5cd15745bb90bcd4b85f95b6”), “id” : 6, “name” : “1111ff1111”, “age” : 33 }
{ “_id” : ObjectId(“5cd152ecbb90bcd4b85f95b4”), “id” : 6, “name” : “1f”, “age” : 33 }
{ “_id” : ObjectId(“5cd1524abb90bcd4b85f95b2”), “id” : 6, “name” : “1f1”, “age” : 33 }
{ “_id” : ObjectId(“5cd15726bb90bcd4b85f95b5”), “id” : 6, “name” : “1ff1”, “age” : 33 }
{ “_id” : ObjectId(“5cd14f49bb90bcd4b85f95ab”), “id” : 1, “name” : “a”, “age” : 20 }
{ “_id” : ObjectId(“5cd14f67bb90bcd4b85f95ac”), “id” : 2, “name” : “b”, “age” : 14 }
{ “_id” : ObjectId(“5cd14f67bb90bcd4b85f95ad”), “id” : 3, “name” : “c”, “age” : 23 }
{ “_id” : ObjectId(“5cd14f67bb90bcd4b85f95ae”), “id” : 4, “name” : “d”, “age” : 40 }
db.t.find().sort({“name”:-1})
{ “_id” : ObjectId(“5cd152a0bb90bcd4b85f95b3”), “id” : 6, “name” : “f1”, “age” : 33 }
{ “_id” : ObjectId(“5cd14f68bb90bcd4b85f95b0”), “id” : 6, “name” : “f”, “age” : 33 }
{ “_id” : ObjectId(“5cd14f67bb90bcd4b85f95af”), “id” : 5, “name” : “e”, “age” : 50 }
{ “_id” : ObjectId(“5cd14f67bb90bcd4b85f95ae”), “id” : 4, “name” : “d”, “age” : 40 }
{ “_id” : ObjectId(“5cd14f67bb90bcd4b85f95ad”), “id” : 3, “name” : “c”, “age” : 23 }
db.t.createIndex({“id”:1})
{
“createdCollectionAutomatically” : false,
“numIndexesBefore” : 1,
“numIndexesAfter” : 2,
“ok” : 1
}
db.values.createIndex({open: 1, close: 1}, {background: true})
{
“createdCollectionAutomatically” : true,
“numIndexesBefore” : 1,
“numIndexesAfter” : 2,
“ok” : 1
}

后面还有复制,分片等等操作,等后续有机会可以深入学习。基本操作都Ok即可。


  1. ^f ↩︎

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

fangwei1234

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值