zoukankan      html  css  js  c++  java
  • 【MongoDB 基础篇】MongoDB增、删、改、查操作

    目录

     

    1 软件环境

    2 基本命令详解

    2.1 连接MongoDB

    2.2 查看帮助命令

    2.3 切换DB

    2.4 查看DB下的集合

    2.5 创建集合

    2.6 插入数据

    2.7 查询操作

    2.8 修改操作

    2.8.1 UPDATE操作方法

    2.8.2 UPDATE操作演示

    2.9 删除操作

    2.9.1 DELETE操作方法

    2.9.2 DELETE操作演示


    1 软件环境

    使用的软件分别为:

    • VirtualBox 5.2
    • Oracle Linux 6.7
    • MongoDB 4.2.0

    2 基本命令详解

    2.1 连接MongoDB

    1)直接进行访问

    在刚安装完MongoDB数据库后,未创建用户前,可以通过mongo命令直接对数据库进行访问:

    [mongod@strong ~]$ mongo
    > show dbs
    admin 0.000GB
    config 0.000GB
    local 0.000GB

    2)通过身份认证访问

    当创建了数据库用户后,使用用户名、密码进行访问,默认端口为27017:

    [mongod@strong ~]$ mongo 192.168.56.102:27017/admin -uroot -p
    > show dbs
    admin 0.000GB
    config 0.000GB
    local 0.000GB
    scott 0.000GB

    2.2 查看帮助命令

    1)查看mongod帮助

    [mongod@strong ~]$ mongod --help.

    2)查看mongo帮助

    > help

    2.3 切换DB

    > use mydb

    2.4 查看DB下的集合

    > show collections

    2.5 创建集合

    1)使用createCollection创建集合

    > db.createCollection("students")

    该方法是显式创建一个集合,若集合不存在,在插入时也会自动创建对应的集合。

    2)insert操作自动创建集合

    > db.emp.insert({id:7369,name:"Smith"})

    2.6 插入数据

    1)插入单条或多条数据

    > db.students.insert({name:"S1",age:25,gender:"M",class:"C1",score:95})
    WriteResult({ "nInserted" : 1 })

    该指令可以插入一个或多个文档

    > db.students.insert([{name:"S4",age:18,gender:"F",class:"C1",score:75},{name:"S5",age:18,gender:"F",class:"C2",score:75}])
    BulkWriteResult({
    "writeErrors" : [ ],
    "writeConcernErrors" : [ ],
    "nInserted" : 2,
    "nUpserted" : 0,
    "nMatched" : 0,
    "nModified" : 0,
    "nRemoved" : 0,
    "upserted" : [ ]
    })

    2)插入单条数据

    > db.students.insertOne({name:"S6",age:21,gender:"M",class:"C2",score:100})
    {
    "acknowledged" : true,
    "insertedId" : ObjectId("5d6a768acdbcfed2e09206c7")
    }

    3)插入多条数据

    > db.students.insertMany([{name:"S2",age:18,gender:"M",class:"C1",score:85},{name:"S3",age:18,gender:"F",class:"C1",score:85}])
    {
    "acknowledged" : true,
    "insertedIds" : [
    ObjectId("5d6a74e4cdbcfed2e09206c3"),
    ObjectId("5d6a74e4cdbcfed2e09206c4")
    ]
    }

    4)循环插入多条数据

    > for(var i=1;i<=20;i++) db.emp.insert({id:i,name:"Test"+i})
    WriteResult({ "nInserted" : 1 })

    2.7 查询操作

    1)查询全部数据

    > db.students.find()
    > db.students.find({})

    2)查询指定条件的数据

    > db.students.find({name:"S1"})

    3)查询指定数据,并显示具体的列

    > db.students.find({name:"S1"},{age:1,score:1})

    4)查询年龄大于20的信息

    > db.students.find({age:{$gt:20}})

    5)查询年龄大于20小于25的信息

    > db.students.find({age:{$gt:20,$lt:25}})

    6)查询班级是C1或C3的信息

    > db.students.find({class:{$in:["C1","C3"]}})

    7)查询年龄大于20且成绩高于90的信息

    > db.students.find({age:{$gt:20},score:{$gt:90}})

    8)查询结果进行排序(升序)

    > db.students.find({class:{$in:["C1","C3"]}}).sort({score:1})

    9)限制返回的结果集

    > db.students.find({class:{$in:["C1","C3"]}}).sort({score:1}).limit(2)

    10)跳过记录,返回结果

    > db.students.find({class:{$in:["C1","C3"]}}).sort({score:1}).limit(2).skip(1)

    11)查询记录总数

    > db.students.find().count()

    12)使用游标返回结果

    > var stus=db.students.find({score:{$gt:80}})
    > while(stus.hasNext()) printjson(stus.next())

    2.8 修改操作

    2.8.1 UPDATE操作方法

    1)db.collection.updateOne()

    更新至多一个满足过滤条件的文档,即使有多个文档满足过滤条件。

    语法:

    db.collection.replaceOne(
    <filter>,
    <replacement>,
    {
    upsert: <boolean>,
    writeConcern: <document>,
    collation: <document>
    }
    )

    2)db.collection.updateMany()

    更新满足条件的所有文档。

    语法:

    db.collection.updateMany(
    <filter>,
    <update>,
    {
    upsert: <boolean>,
    writeConcern: <document>,
    collation: <document>,
    arrayFilters: [ <filterdocument1>, ... ]
    }
    )

    3)db.collection.replaceOne()

    取代满足条件的一个文档,即使有多个文档满足条件。

    语法:

    db.collection.replaceOne(
    <filter>,
    <replacement>,
    {
    upsert: <boolean>,
    writeConcern: <document>,
    collation: <document>
    }
    )

    4)db.collection.update()

    更新满足条件的文档,默认只更新一个文档,可以通过指定multi选项为True更新多个文档。

    语法:

    db.collection.update(
    <query>,
    <update>,
    {
    upsert: <boolean>,
    multi: <boolean>,
    writeConcern: <document>,
    collation: <document>,
    arrayFilters: [ <filterdocument1>, ... ],
    hint: <document|string> // Available starting in MongoDB 4.2
    }
    )

    2.8.2 UPDATE操作演示

    1)初始化数据集合

    > db.inventory.insertMany( [
    ... { item: "canvas", qty: 100, size: { h: 28, w: 35.5, uom: "cm" }, status: "A" },
    ... { item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
    ... { item: "mat", qty: 85, size: { h: 27.9, w: 35.5, uom: "cm" }, status: "A" },
    ... { item: "mousepad", qty: 25, size: { h: 19, w: 22.85, uom: "cm" }, status: "P" },
    ... { item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "P" },
    ... { 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" },
    ... { item: "sketchbook", qty: 80, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
    ... { item: "sketch pad", qty: 95, size: { h: 22.85, w: 30.5, uom: "cm" }, status: "A" }
    ... ] );

    2)db.collection.updateOne()

    > db.inventory.updateOne({item:"paper"},{$set:{status:"P"}})
    { "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
    
    
    > db.inventory.updateOne({},{$set:{"size.h":30}})
    { "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

    3)db.collection.updateMany()

    > db.inventory.updateMany({qty:{$gt:80}},{$set:{"size.uom":"cm"}})
    { "acknowledged" : true, "matchedCount" : 4, "modifiedCount" : 1 }

    4)db.collection.replaceOne()

    > db.inventory.replaceOne({item:"paper"},{item:"paper_test",qty:90,location:"Shenzhen",create_date:ISODate()})
    { "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

    该操作替换除了_id之外整个文档内容。

    5)db.collection.update()

    > db.inventory.update({qty:{$gte:80}},{$set:{status:"N"}})
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
    
    
    > db.inventory.update({qty:{$gte:80}},{$set:{status:"N"}},{multi:true})
    WriteResult({ "nMatched" : 4, "nUpserted" : 0, "nModified" : 3 })

    2.9 删除操作

    2.9.1 DELETE操作方法

    1)db.collection.deleteMany()

    删除满足条件的文档,删除所有文档可指定空或者{}。

    语法:

    db.collection.deleteMany(
    <filter>,
    {
    writeConcern: <document>,
    collation: <document>
    }
    )

    2)db.collection.deleteOne()

    删除满足条件的一个文档,即使有多个文档满足条件。

    语法:

    db.collection.deleteOne(
    <filter>,
    {
    writeConcern: <document>,
    collation: <document>
    }
    )

    3)db.collection.remove()

    从集合中移除文档,有两种用法,移除所有文档或一个文档。

    语法:

    db.collection.remove(
    <query>,
    <justOne>
    )

    2.9.2 DELETE操作演示

    1)db.collection.deleteMany()

    > db.inventory.deleteMany({qty:{$gte:80}})
    { "acknowledged" : true, "deletedCount" : 4 }

    2)db.collection.deleteOne()

    > db.inventory.deleteOne({status:"N"})
    { "acknowledged" : true, "deletedCount" : 1 }

    3)db.collection.remove()

    > db.inventory.remove({},{justOne:true})
    WriteResult({ "nRemoved" : 1 })
    
    
    > db.inventory.remove({})
    WriteResult({ "nRemoved" : 4 })

  • 相关阅读:
    Jenkins分享
    Java静态绑定和动态绑定
    SpringBoot中RedisTemplate订阅发布对象
    Idea项目:Failed to create a Maven project ‘…pom.xml’ already exists in VFS 解决
    Java Web不能不懂的知识
    Required String parameter 'id' is not present
    Hive使用druid做连接池代码实现
    Docker Toolbox常见错误解决方案
    初学者手册-MyBatis踩坑记(org.apache.ibatis.binding.BindingException)
    SpringMVC日志管理(自定义异常及自定义注解)
  • 原文地址:https://www.cnblogs.com/alen-liu-sz/p/12975598.html
Copyright © 2011-2022 走看看