MongoDB(四):数据类型、插入文档、查询文档
1. 数据类型
MongoDB支持许多数据类型。
字符串 - 这是用于存储数据的最常用的数据类型。MongoDB中的字符串必须为UTF-8
。
整型 - 此类型用于存储数值。 整数可以是32
位或64
位,具体取决于服务器。
布尔类型 - 此类型用于存储布尔值(true
/ false
)值。
双精度浮点数 - 此类型用于存储浮点值。
最小/最大键 - 此类型用于将值与最小和最大BSON
元素进行比较。
数组 - 此类型用于将数组或列表或多个值存储到一个键中。
时间戳 - ctimestamp
,当文档被修改或添加时,可以方便地进行录制。
对象 - 此数据类型用于嵌入式文档。
对象 - 此数据类型用于嵌入式文档。
Null - 此类型用于存储Null
值。
符号 - 该数据类型与字符串相同; 但是,通常保留用于使用特定符号类型的语言。
日期 - 此数据类型用于以UNIX时间格式存储当前日期或时间。您可以通过创建日期对象并将日,月,年的日期进行指定自己需要的日期时间。
对象ID - 此数据类型用于存储文档的ID。
二进制数据 - 此数据类型用于存储二进制数据。
代码 - 此数据类型用于将JavaScript代码存储到文档中。
正则表达式 - 此数据类型用于存储正则表达式。
2. 插入文档
2.1 insert()和save方法插入文档
引导数据插入到MongoDB集合中,需要使用MongoDB的insert()或save()方法。
语法:
>db.COLLECTION_NAME.insert(document)
例子:
>db.mycol.insert({
_id: 100,
title: 'MongoDB Overview',
description: 'MongoDB is no sql database',
by: 'yiibai tutorials',
url: 'http://www.yiibai.com',
tags: ['mongodb', 'database', 'NoSQL'],
likes: 100,
})
这里 mycol的英文集合的名称,是在前一章创建的。如果数据库中不存在集合,则MongoDB将创建此集合,然后将文档插入到该集合中。
- 一个 4 字节的值,表示自 Unix 纪元以来的秒数
- 一个 3 字节的机器标识符
- 一个 2 字节的进程 ID
- 一个 3 字节的计数器,以随机值开始
_id: ObjectId(4 bytes timestamp, 3 bytes machine id, 2 bytes process id,
3 bytes incrementer)
要在单个查询中插入多个文档,可以在insert()命令中传递文档数组。如下所示:
> db.mycol.insert([
{
_id: 101,
title: 'MongoDB Guide',
description: 'MongoDB is no sql database',
by: 'xhh tutorials',
url: 'http://www.baidu.com',
tags: ['mongodb', 'database', 'NoSQL'],
likes: 100
}, {
_id: 102,
title: 'NoSQL Database',
description: "NoSQL database doesn't have tables",
by: 'xhh tutorials',
url: 'http://www.baidu.com',
tags: ['mongodb', 'database', 'NoSQL'],
likes: 210,
comments: [
{
user:'user1',
message: 'My first comment',
dateCreated: new Date(2017,11,10,2,35),
like: 0
}
]
},
{
_id: 104,
title: 'Python Quick Guide',
description: "Python Quick start ",
by: 'xhh tutorials',
url: 'http://www.baidu.com',
tags: ['Python', 'database', 'NoSQL'],
likes: 30,
comments: [
{
user:'user1',
message: 'My first comment',
dateCreated: new Date(2018,11,10,2,35),
like: 590
}
]
}
])
2.2 其他插入文档的方法
2.2.1 db.collection.insertOne()方法
如果将文档_id分配给MongoDB,会自动将_id与其ObjectId值添加到新文档。
db.inventory.insertOne(
{ item: "canvas", qty: 100, tags: ["cotton"], size: { h: 28, w: 35.5, uom: "cm" } }
)
方法返回包含新插入的文档的_id细分值的文档。
> db.inventory.insertOne(
... { item: "canvas", qty: 100, tags: ["cotton"], size: { h: 28, w: 35.5, uom: "cm" } }
... )
{
"acknowledged" : true,
"insertedId" : ObjectId("5955220846be576f199feb55")
}
>
2.2.2 db.collection.insertMany()方法
db.inventory.insertMany([
{ item: "journal", qty: 25, tags: ["blank", "red"], size: { h: 14, w: 21, uom: "cm" } },
{ item: "mat", qty: 85, tags: ["gray"], size: { h: 27.9, w: 35.5, uom: "cm" } },
{ item: "mousepad", qty: 25, tags: ["gel", "blue"], size: { h: 19, w: 22.85, uom: "cm" } }
])
方法返回包含新插入的文档的_id细分值的文档。
> db.inventory.insertMany([
... { item: "journal", qty: 25, tags: ["blank", "red"], size: { h: 14, w: 21, uom: "cm" } },
... { item: "mat", qty: 85, tags: ["gray"], size: { h: 27.9, w: 35.5, uom: "cm" } },
... { item: "mousepad", qty: 25, tags: ["gel", "blue"], size: { h: 19, w: 22.85, uom: "cm" } }
... ])
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("59552c1c46be576f199feb56"),
ObjectId("59552c1c46be576f199feb57"),
ObjectId("59552c1c46be576f199feb58")
]
}
>
3. 查询文档
3.1 find()方法
要从MongoDB集合查询数据,需要使用MongoDB的find()方法。
语法:
>db.COLLECTION_NAME.find(document)
方法将以非结构化的方式显示所有文档。
3.2 pretty()方法
> db.mycol.find().pretty()
例子:
>db.mycol.find().pretty()
{
"_id": 100,
"title": "MongoDB Overview",
"description": "MongoDB is no sql database",
"by": "yiibai tutorials",
"url": "http://www.yiibai.com",
"tags": ["mongodb", "database", "NoSQL"],
"likes": "100"
}
>
除了find()方法外,还有一个findOne()方法,它只返回一个文档。
3.3 MongoDB与RDBMS的等效Where子句
要在一些条件的基础上查询文档,可以使用以下操作。
操作 | 语法 | 示例 | RDBMS等效语句 |
---|---|---|---|
相等 | {<key>:<value>} |
db.mycol.find({"by":"yiibai"}).pretty() |
where by = 'yiibai' |
小于 | {<key>:{$lt:<value>}} |
db.mycol.find({"likes":{$lt:50}}).pretty() |
where likes < 50 |
小于等于 | {<key>:{$lte:<value>}} |
db.mycol.find({"likes":{$lte:50}}).pretty() |
where likes <= 50 |
大于 | {<key>:{$gt:<value>}} |
db.mycol.find({"likes":{$gt:50}}).pretty() |
where likes > 50 |
大于等于 | {<key>:{$gte:<value>}} |
db.mycol.find({"likes":{$gte:50}}).pretty() |
where likes >= 50 |
不等于 | {<key>:{$ne:<value>}} |
db.mycol.find({"likes":{$ne:50}}).pretty() |
where likes != 50 |
3.4 MongoDB中的AND操作符
语法:
在find()方法中,如果通过‘,’将它们分开传递多个键,则MongoDB将其视为AND条件。
>db.mycol.find(
{
$and: [
{key1: value1}, {key2:value2}
]
}
).pretty()
例子:
以下示例将显示由“xhh tutorials”编写并且标题为“MongoDB Overview”的所有教程。
> db.mycol.find({$and:[{"by":"xhh tutorials"},{"title": "MongoDB Overview"}]}).pretty()
{
"_id" : 100,
"title" : "MongoDB Overview",
"description" : "MongoDB is no sql database",
"by" : "yiibai tutorials",
"url" : "https://www.cnblogs.com/liuhui0308/",
"tags" : [
"mongodb",
"database",
"NoSQL"
],
"likes" : 100
}
对于上面给出的例子,等效的SQL where子句是:
SELECT * FROM mycol where by ='yiibai tutorials' AND title ='MongoDB Overview'
可以在find子句中传递任意数量的键值。
35 MongoDB中的OR操作符
>db.mycol.find(
{
$or: [
{key1: value1}, {key2:value2}
]
}
).pretty()
例子:
以下示例将显示由“xhh tutorials”编写并且标题为“MongoDB Overview”的所有教程。
>db.mycol.find({$or:[{"by":"xhh tutorials"},{"title": "MongoDB Overview"}]}).pretty()
{
"_id": 100,
"title": "MongoDB Overview",
"description": "MongoDB is no sql database",
"by": "yiibai tutorials",
"url": "https://www.cnblogs.com/liuhui0308/",
"tags": [
"mongodb",
"database",
"NoSQL"
],
"likes": "100"
}
>
3.6 AND和OR联合使用
10
以及标题是“MongoDB”或者“xhh tutorials”的所有文档。SELECT * FROM mycol where likes> 10 AND(by ='yiibai tutorials' OR title ='MongoDB Overview')
代码:
>db.mycol.find({"likes": {$gt:10}, $or: [{"by": "yiibai tutorials"},
{"title": "MongoDB Overview"}]}).pretty()
{
"_id": 100,
"title": "MongoDB Overview",
"description": "MongoDB is no sql database",
"by": "yiibai tutorials",
"url": "http://www.yiibai.com",
"tags": ["mongodb", "database", "NoSQL"],
"likes": "100"
}
>
3.7 查询嵌入/嵌套文档
数据准备:
db.inventory.insertMany( [
{ item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
{ item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "A" },
{ item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },
{ item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },
{ item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" }
]);
3.4.1 匹配嵌入/嵌套文档
要在作为嵌入/嵌套文档的字段上指定相等条件,请使用查询过滤器文档{<field>:<value>},其中<value>是要匹配的文档。
db.inventory.find( { size: { h: 14, w: 21, uom: "cm" } } )
整个嵌入式文档中的相等匹配需要精确匹配指定的<value>文档,包括字段顺序。
例如,以下查询与库存(inventory)集合中的任何文档不匹配:
db.inventory.find( { size: { w: 21, h: 14, uom: "cm" } }
3.4.2 查询嵌套字段
要在嵌入/嵌套文档中的字段上指定查询条件,请使用点符号(“field.nestedField
”)。在嵌套字段上指定等于匹配。
db.inventory.find( { "size.uom": "in" } )
3.4.3 使用查询运算符指定匹配
{ <field1>: { <operator1>: <value1> }, ... }
以下查询使用size字段中嵌入的字段h中的小于运算符($lt):
db.inventory.find( { "size.h": { $lt: 15 } } )
3.4.4 指定AND条件
db.inventory.find( { "size.h": { $lt: 15 }, "size.uom": "in", status: "D" } )
MongoDB(四):数据类型、插入文档、查询文档的更多相关文章
- MongoDB 教程(八):查询文档、条件操作符
MongoDB 查询文档 MongoDB 查询文档使用 find() 方法. find() 方法以非结构化的方式来显示所有文档. MongoDB 查询数据的语法格式如下: db.collection. ...
- MongoDB基础教程系列--第四篇 MongoDB 查询文档
查询文档 查询文档可以用 find() 方法查询全部文档,可以用 findOne() 查询第一个文档,当然还可以根据 条件操作符 和 $type操作符 查询满足条件的文档. find() 和 find ...
- MongoDB快速入门(四)- 插入文档
插入文档 将数据插入到MongoDB集合,需要使用MongoDB 的 insert() 方法. 语法 insert()命令的基本语法如下: >db.COLLECTION_NAME.insert( ...
- SpringMVC MongoDB之“基本文档查询(Query、BasicQuery)”
一.简介 spring Data MongoDB提供了org.springframework.data.mongodb.core.MongoTemplate对MongoDB的CRUD的操作,上一篇我 ...
- Spring Data MongoDB 三:基本文档查询(Query、BasicQuery)(一)
一.简单介绍 Spring Data MongoDB提供了org.springframework.data.mongodb.core.MongoTemplate对MongoDB的CRUD的操作,上一 ...
- Spring Data MongoDB 三:基本文档查询(Query、BasicQuery
一.简介 spring Data MongoDB提供了org.springframework.data.mongodb.core.MongoTemplate对MongoDB的CRUD的操作,上一篇我 ...
- MongoDB入门---文档查询之$type操作符&limit方法&skip方法&简单排序(sort)操作
上一篇文章呢,已经分享过了一部分查询操作了,这篇文章呢?就来继续分享哈.接下来呢我们直接看MongoDB中的$type操作符哈.它呢是基于BSON类型来检索集合中匹配的数据类型,并且返回结果,在Mon ...
- Spring Data MongoDB 四:基本文档改动(update)(一)
Spring Data MongoDB 三:基本文档查询(Query.BasicQuery)(一) 学习MongoDB 二:MongoDB加入.删除.改动 一.简单介绍 Spring Data Mo ...
- MongoDB入门---文档查询操作之条件查询&and查询&or查询
经过前几天的学习之路,今天终于到了重头戏了.那就是文档查询操作.话不多说哈,直接看下语法: db.collection.find(query, projection) query :可选,使用查询操作 ...
随机推荐
- Codeforces Round #452 (Div. 2) A B C
Codeforces Round #452 (Div. 2) A Splitting in Teams 题目链接: http://codeforces.com/contest/899/problem/ ...
- .Net Core+Vue.js模块化前后端分离快速开发框架NetModular更新日志(2019-12-08)
源码 GitHub:https://github.com/iamoldli/NetModular 码云:https://gitee.com/laoli/NetModular 欢迎star~ 文档 ht ...
- Netty实现丢弃服务协议(Netty4.X学习一)
何为丢弃服务(Discard Protocol),丢弃服务就是一个协议,是最简单的协议,它的作用是接受到什么就丢弃什么,它对调试网路状态有一定的用处.基于TCP的丢弃服务,服务器实现了丢弃丢弃协议,服 ...
- 脚本shell每小时递增运行task
下面 hello 是开始时间, world 是结束时间 #!/bin/bash START=$(date +%s); hello="20160911 00" world=" ...
- 压缩感知重构算法之IHT算法python实现
压缩感知重构算法之OMP算法python实现 压缩感知重构算法之CoSaMP算法python实现 压缩感知重构算法之SP算法python实现 压缩感知重构算法之IHT算法python实现 压缩感知重构 ...
- windows系统安装git
一.下载git的安装包 git官网的下载地址:https://git-scm.com/download/win 选择自己的机型进行安装. 二.安装配置 一直点下一步就可以 安装完毕之后,打开电脑命令窗 ...
- CoderForces Round54 (A~E)
ProblemA Minimizing the String 题目链接 题解:这一题读完题就写了吧.就是让你删除一个字母,使得剩下的字符组成的字符串的字典序最小:我们只要第一个当前位置的字符比下一个字 ...
- CoderFocers-620C
There are n pearls in a row. Let's enumerate them with integers from 1 to n from the left to the rig ...
- (全国多校重现赛一)E-FFF at Valentine
At Valentine's eve, Shylock and Lucar were enjoying their time as any other couples. Suddenly, LSH, ...
- 洛谷 题解 P1600 【天天爱跑步】 (NOIP2016)
必须得说,这是一道难题(尤其对于我这样普及组205分的蒟蒻) 提交结果(NOIP2016 天天爱跑步): OJ名 编号 题目 状态 分数 总时间 内存 代码 / 答案文件 提交者 提交时间 Libre ...