使用 insert 完成插入操作

操作格式:
db.<集合>.insertOne(<JSON对象>)
db.<集合>.insertMany([<JSON 1>, <JSON 2>, …<JSON n>])
示例:
db.fruit.insertOne({name: "apple"})
db.fruit.insertMany([
{name: "apple"},
{name: "pear"},
{name: "orange"}
])

> db.fruit.insertOne({name: "apple"})
{
"acknowledged" : true,
"insertedId" : ObjectId("5e7179e3f4d1e2208586ff4a")
}
> db.fruit.insertMany([
... {name: "apple"},
... {name: "pear"},
... {name: "orange"}
... ])
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("5e7179e6f4d1e2208586ff4b"),
ObjectId("5e7179e6f4d1e2208586ff4c"),
ObjectId("5e7179e6f4d1e2208586ff4d")
]
}
> db.fruit.find()
{ "_id" : ObjectId("5e7179e3f4d1e2208586ff4a"), "name" : "apple" }
{ "_id" : ObjectId("5e7179e6f4d1e2208586ff4b"), "name" : "apple" }
{ "_id" : ObjectId("5e7179e6f4d1e2208586ff4c"), "name" : "pear" }
{ "_id" : ObjectId("5e7179e6f4d1e2208586ff4d"), "name" : "orange" }
> db.fruit.drop()
true

view

使用 find 查询文档

关于 find:
• find 是 MongoDB 中查询数据的基本指令,相当于 SQL 中的 SELECT 。
• find 返回的是游标。

find 示例:
db.movies.find( { "year" : 1975 } ) //单条件查询
db.movies.find( { "year" : 1989, "title" : "Batman" } ) //多条件and查询
db.movies.find( { $and : [ {"title" : "Batman"}, { "category" : "action" }] } ) // and的另一种形式
db.movies.find( { $or: [{"year" : 1989}, {"title" : "Batman"}] } ) //多条件or查询
db.movies.find( { "title" : /^B/} ) //按正则表达式查找

> db.fruit.find()
{ "_id" : ObjectId("5e7179e3f4d1e2208586ff4a"), "name" : "apple" }
{ "_id" : ObjectId("5e7179e6f4d1e2208586ff4b"), "name" : "apple" }
{ "_id" : ObjectId("5e7179e6f4d1e2208586ff4c"), "name" : "pear" }
{ "_id" : ObjectId("5e7179e6f4d1e2208586ff4d"), "name" : "orange" }

查询条件对照表

查询逻辑对照表

查询逻辑运算符

● $lt: 存在并小于
● $lte: 存在并小于等于
● $gt: 存在并大于
● $gte: 存在并大于等于
● $ne: 不存在或存在但不等于
● $in: 存在并在指定数组中
● $nin: 不存在或不在指定数组中
● $or: 匹配两个或多个条件中的一个
● $and: 匹配全部条件

使用 find 搜索子文档

find 支持使用“field.sub_field”的形式查询子文档。假设有一个文档:
db.fruit.insertOne({
name: "apple",
from: {
country: "China",
province: "Guangdon"
}
})
考虑以下查询的意义:
db.fruit.find( { "from.country" : "China" } )
db.fruit.find( { "from" : {country: "China"} } )
> db.fruit.drop()
true
> db.fruit.insertOne({
... name: "apple",
... from: {
... country: "China",
... province: "Guangdon"
... }
... })
{
"acknowledged" : true,
"insertedId" : ObjectId("5e718f3cf4d1e2208586ff4e")
}
> db.fruit.find( { "from.country" : "China" } )
{ "_id" : ObjectId("5e718f3cf4d1e2208586ff4e"), "name" : "apple", "from" : { "country" : "China", "province"} }
> db.fruit.find( { "from" : {country: "China"} } ) #错误的写法

使用 find 搜索数组

● find 支持对数组中的元素进行搜索。假设有一个文档:
db.fruit.insert([
{ "name" : "Apple", color: ["red", "green" ] },
{ "name" : "Mango", color: ["yellow", "green"] }
])
● 考虑以下查询的意义:
db.fruit.find({color: "red"})
db.fruit.find({$or: [{color: "red"}, {color: "yellow"}]} )

使用 find 搜索数组中的对象

考虑以下文档,在其中搜索
db.movies.insertOne( {
"title" : "Raiders of the Lost Ark",
"filming_locations" : [
{ "city" : "Los Angeles", "state" : "CA", "country" :
"USA" },
{ "city" : "Rome", "state" : "Lazio", "country" : "Italy" },
{ "city" : "Florence", "state" : "SC", "country" : "USA" }
]
})
• // 查找城市是 Rome 的记录
• db.movies.find({"filming_locations.city": "Rome"})

在数组中搜索子对象的多个字段时,如果使用 $elemMatch,它表示必须是同一个
子对象满足多个条件。考虑以下两个查询:
db.getCollection('movies').find({
"filming_locations.city": "Rome",
"filming_locations.country": "USA"
})
db.getCollection('movies').find({
"filming_locations": {
$elemMatch:{"city":"Rome", "country": "USA"}
}
})

控制 find 返回的字段

● find 可以指定只返回指定的字段;
● _id字段必须明确指明不返回,否则默认返回;
● 在 MongoDB 中我们称这为投影(projection);

> db.movies.find().pretty()
{
"_id" : ObjectId("5e71dca5f4d1e2208586ff51"),
"title" : "Raiders of the Lost Ark",
"filming_locations" : [
{
"city" : "Los Angeles",
"state" : "CA",
"country" : "USA"
},
{
"city" : "Rome",
"state" : "Lazio",
"country" : "Italy"
},
{
"city" : "Florence",
"state" : "SC",
"country" : "USA"
}
]
}
> db.movies.find({{},{"_id":0,"title":1})
...
...
> db.movies.find({},{"_id":0,"title":1}) # 0 代表不返回,1代表返回
{ "title" : "Raiders of the Lost Ark" } > db.movies.find({},{"_id":1,"title":1}).pretty()
{
"_id" : ObjectId("5e71dca5f4d1e2208586ff51"),
"title" : "Raiders of the Lost Ark"
}

使用 remove 删除文档

● remove 命令需要配合查询条件使用;
● 匹配查询条件的的文档会被删除;
● 指定一个空文档条件会删除所有文档;
● 以下示例:
db.testcol.remove( { a : 1 } ) // 删除a 等于1的记录
db.testcol.remove( { a : { $lt : 5 } } ) // 删除a 小于5的记录
db.testcol.remove( { } ) // 删除所有记录
db.testcol.remove() //报错

> db.movies.remove()
2020-03-18T08:47:40.340+0000 E QUERY [js] uncaught exception: Error: remove needs a query :
DBCollection.prototype._parseRemove@src/mongo/shell/collection.js:357:15
DBCollection.prototype.remove@src/mongo/shell/collection.js:384:18
@(shell):1:1
> db.fruit.drop()
true

使用 update 更新文档

● Update 操作执行格式:db.<集合>.update(<查询条件>, <更新字段>)
● 以以下数据为例:
db.fruit.insertMany([
{name: "apple"},
{name: "pear"},
{name: "orange"}
])

> db.fruit.updateOne({name:"apple"},{$set:{from:"China"}})
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
> db.fruit.find().pretty()
{
"_id" : ObjectId("5e71e341dcd58a45bbdee312"),
"name" : "apple",
"from" : "China"
}
{ "_id" : ObjectId("5e71e341dcd58a45bbdee313"), "name" : "pear" }
{ "_id" : ObjectId("5e71e341dcd58a45bbdee314"), "name" : "orange" }

使用 updateOne 表示无论条件匹配多少条记录,始终只更新第一条;
● 使用 updateMany 表示条件匹配多少条就更新多少条;
● updateOne/updateMany 方法要求更新条件部分必须具有以下之一,否则将报错:
• $set/$unset
• $push/$pushAll/$pop
• $pull/$pullAll
• $addToSet
● // 报错
db.fruit.updateOne({name: "apple"}, {from: "China"})

使用 update 更新数组

● $push: 增加一个对象到数组底部
● $pushAll: 增加多个对象到数组底部
● $pop: 从数组底部删除一个对象
● $pull: 如果匹配指定的值,从数组中删除相应的对象
● $pullAll: 如果匹配任意的值,从数据中删除相应的对象
● $addToSet: 如果不存在则增加一个值到数组

使用 drop 删除集合

● 使用 db.<集合>.drop() 来删除一个集合
● 集合中的全部文档都会被删除
● 集合相关的索引也会被删除
db.colToBeDropped.drop()

使用 dropDatabase 删除数据库

● 使用 db.dropDatabase() 来删除数据库
● 数据库相应文件也会被删除,磁盘空间将被释放
use tempDB
db.dropDatabase()
show collections // No collections
show dbs // The db is gone

06丨MongoDB基本操作的更多相关文章

  1. MongoDB 基本操作和聚合操作

    一 . MongoDB 基本操作 基本操作可以简单分为查询.插入.更新.删除. 1 文档查询 作用 MySQL SQL  MongoDB  所有记录  SELECT * FROM users;  db ...

  2. 【MongoDB详细使用教程】二、MongoDB基本操作

    目录 数据类型 数据库操作 集合操作 数据操作 增 查 改 修改整行 修改指定字段的值 删 数据类型 MongoDB常见类型 说明 Object ID 文档ID String 字符串,最常用,必须是有 ...

  3. MongoDB【第三篇】MongoDB基本操作

    MongoDB的基本操作包括文档的创建.删除.和更新 文档插入 1.插入 #查看当前都有哪些数据库 > show dbs; local 0.000GB tim 0.000GB #使用 tim数据 ...

  4. mongodb基本操作的学习

    1.基本操作: 如何安装?创建存放数据的文件夹 robomongo: 图形化管理工具 create -->save -->connect 创建数据库:use Database_name 检 ...

  5. 30分钟让你了解MongoDB基本操作

    今天记录下MongoDB的基本操作,这只是最基本的,所以是应该掌握的. 数据库 数据库是一个物理容器集合.每个数据库都有自己的一套文件系统上的文件.一个单一的MongoDB服务器通常有多个数据库. 集 ...

  6. mongodb基本操作及存储图片显示方案

    先介绍下mongodb的基本操作及使用 第一部:开启安全性验证 如果需要给MongoDB数据库使用安全验证,则需要用--auth开启安全性检查,则只有数据库认证的用户才能执行读写操作,开户安全性检查, ...

  7. 30分钟让你了解MongoDB基本操作(转)

    今天记录下MongoDB的基本操作,这只是最基本的,所以是应该掌握的. 数据库 数据库是一个物理容器集合.每个数据库都有自己的一套文件系统上的文件.一个单一的MongoDB服务器通常有多个数据库. 集 ...

  8. MongoDB基本操作(包括插入、修改、子节点排序等)

    一.基本操作 1.新增文章 db.article.insert({title:"今天天气很好",content:"我们一起去春游",_id:1}) 2.新增一条 ...

  9. MongoDB(课时3 MongoDB基本操作)

    3.3 MongoDB的基本操作 在MongoDB数据库里面存在数据库的概念,但没有模式(所有的信息都是按照文档保存的),保存数据的结构是BSON结构,只不过在进行一些数据处理的时候才会使用到Mong ...

随机推荐

  1. 【CTF】XCTF Misc 心仪的公司 & 就在其中 writeup

    前言 这两题都是Misc中数据包的题目,一直觉得对数据包比较陌生,不知道怎么处理. 这里放两道题的wp,第一题strings命令秒杀觉得非常优秀,另外一题有涉及RSA加密与解密(本文不具体讨论RSA非 ...

  2. CppCon 2019 | Back to Basics: RAII and The Rule of Zero

    本文整理了Arthur O'Dwyer在CppCon 2019上关于RAII的演讲,演讲的slides可以在此链接进行下载. 在C++程序中,我们往往需要管理各种各样的资源.资源通常包括以下几种: A ...

  3. Ambassador-05-自动重试

    自动重试定义: retry_policy: retry_on: <string> num_retries: <integer> per_try_timeout: <str ...

  4. HUAWEI AppGallery Connect获得SOC国际权威认证,多举措保护信息和隐私安全

    近日,华为应用市场AppGallery Connect(简称AGC)一次性成功通过国际权威标准组织"美国注册会计师协会(AICPA)"认定的SOC1 Type2.SOC2 Type ...

  5. Andy‘s First Dictionary UVA - 10815

      Andy, 8, has a dream - he wants to produce his very own dictionary. This is not an easy task for h ...

  6. POJ 1201 差分约束(集合最小元素个数)

    题意:       给你一个集合,然后有如下输入,a ,b ,c表示在范围[a,b]里面有至少有c个元素,最后问你整个集合最少多少个元素. 思路:       和HDU1384一模一样,首先这个题目可 ...

  7. hdu1074 状态压缩dp+记录方案

    题意:       给你一些作业,每个作业有自己的结束时间和花费时间,如果超过结束时间完成,一天扣一分,问你把n个作业完成最少的扣分,要求输出方案. 思路:       状态压缩dp,记录方案数的地方 ...

  8. ResNet学习笔记

    ResNet学习笔记 前言 这篇文章实在看完很多博客之后写的,需要读者至少拥有一定的CNN知识,当然我也不知道需要读者有什么水平,所以可能对一些很入门的基本的术语进行部分的解释,也有可能很多复杂的术语 ...

  9. android之布局优化

    android中提供了<include />.<merge />.<ViewStub />三种优化布局. 1.<include /> <inclu ...

  10. 序列化-JDK自带Serializable

    如下代码示例:实现了Serializable接口(强制)的类,可以通过ObjectOutputStream的writeObject()方法转为字节流. 字节流通过ObjectInputStream的r ...