06丨MongoDB基本操作
阅读原文时间:2023年07月10日阅读:1

操作格式:
db.<集合>.insertOne()
db.<集合>.insertMany([, , …])
示例:
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 是 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 命令需要配合查询条件使用;
● 匹配查询条件的的文档会被删除;
● 指定一个空文档条件会删除所有文档;
● 以下示例:
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 操作执行格式: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: 如果不存在则增加一个值到数组

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

使用 dropDatabase 删除数据库

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

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章