玩转MongoDB4.0(MongoDB基础总结)

基础:

  • 是非关系型数据库
  • 文档存储

1、显示当前的所有数据库

  • show dbs
  • show databases;

2、使用数据库

  • use 数据库

3、查看当前数据库

  • db

4、显示数据库中所有的集合

  • show collections

5、查看docker日志

  • docker logs docker_mongodb(mongodb的docker容器名字)

6、Mongo Express是一个基于网络的MongoDB数据库管理界面

  • docker pull mongo-express  // 下载mongo-express镜像
  • docker run --link docker_mongodb:mongo -p 8081:8081 mongo-express  //运行mongo-express,docker_mongodb是docker中mongodb容器名字

7、mongo shell是用来操作MongoDB的javascript客户端界面

  • 运行mogog shell
    docker exec -it docker_mongodb mongo
  • exit 退出

8、数据库的CRUD(增删改查)操作

  • Create、Read、Update、Delete
  • 文档主键: _id
  • 文档主建有唯一性
  • 支出所有数据类型(除了数组)
  • 自动生成主建(12字节,前四个是时间)

9、创建文档

  • db.collection.insert()
    1、db.insertOne() 一次只能插入一个文档
    db.accounts.insertOne({name:"nanzai", balance: 3500})
    
    {
    	"acknowledged" : true,
    	"insertedId" : ObjectId("5e157856665014c2c50ea538")
    }
    


    2、db.insertMany()必须插入多个文档
    db.accounts.insertMany([{name:"xinzai", balance: 500}, {name:"xinge", balance:600}])
    
    {
    	"acknowledged" : true,
    	"insertedIds" : [
    		ObjectId("5e1576cc665014c2c50ea536"),
    		ObjectId("5e1576cc665014c2c50ea537")
    	]
    }
    

    3、db.collection.inset()可以插入一个或者多个文档
    db.accounts.insert([{name: "jack",balance: 2000, contact: ["137111111","陕西省","China"]},{name: "karen", balance: 3000, contact: ["18391000411", "湖南省", "china"]}])
    
    BulkWriteResult({
    	"writeErrors" : [ ],
    	"writeConcernErrors" : [ ],
    	"nInserted" : 2,
    	"nUpserted" : 0,
    	"nMatched" : 0,
    	"nModified" : 0,
    	"nRemoved" : 0,
    	"upserted" : [ ]
    })
    
    db.accounts.insert({name: "ke", balance: 1800, "contact": [["1754684641","195324664654"], "陕西省", "China"]})
    
    WriteResult({ "nInserted" : 1 })
  • db.collection.save()
  • 创建多个文档

10、查找文档
 数组操作符:all

  • db.collection.find()查询所有文档
    db.accounts.find()
    
    { "_id" : ObjectId("5e1331591f342ac67bb98e52"), "name" : "xiaoke", "balance" : 1000 }
    { "_id" : ObjectId("5e1332d11f342ac67bb98e53"), "name" : "one", "balance" : 1000 }
    { "_id" : ObjectId("5e13331e1f342ac67bb98e54"), "name" : "one", "balance" : 1000 }
    { "_id" : ObjectId("5e1336e91f342ac67bb98e57"), "name" : "jack", "balance" : 2000, "contact" : [ "137111111", "陕西省", "China" ] }
    { "_id" : ObjectId("5e1336e91f342ac67bb98e58"), "name" : "karen", "balance" : 3000, "contact" : [ "18391000411", "湖南省", "china" ] }
    { "_id" : ObjectId("5e1337dc1f342ac67bb98e59"), "name" : "xiaoke", "balance" : 1000, "contact" : [ "1371811111", "山西省", "China" ] }
    { "_id" : ObjectId("5e1337dc1f342ac67bb98e5a"), "name" : "xiaowang", "balance" : 1500, "contact" : [ "18891000411", "湖南省", "china" ] }
    
  • 读取联系地址位于China陕西省的银行账户信息
    db.accounts.find({contact:{$all:["China","陕西省"]}})
    
    { "_id" : ObjectId("5e1336e91f342ac67bb98e57"), "name" : "jack", "balance" : 2000, "contact" : [ "137111111", "陕西省", "China" ] }
    
  • 读取联系电话包含1754684641和195324664654的银行账户文档
    db.accounts.find( { "contact":{ $all: [["1754684641", "195324664654"]]}})
    
    { "_id" : ObjectId("5e133b15738962fb118b2554"), "name" : "ke", "balance" : 1800, "contact" : [ [ "1754684641", "195324664654" ], "陕西省", "China" ] }
    
    
  • .pretty()打印的更加清楚
     

    db.accounts.find({name: "xin"}).pretty()
    {
    	"_id" : ObjectId("5e154a6d297892ae4951650d"),
    	"name" : "xin",
    	"balance" : 5000,
    	"contact" : [
    		"1204557644",
    		"广东省",
    		"china"
    	]
    }
    {
    	"_id" : ObjectId("5e154a79297892ae4951650e"),
    	"name" : "xin",
    	"balance" : 5000,
    	"contact" : [
    		"1204557644",
    		"广东省",
    		"china"
    	]
    }
    

elemMatch 任一操作符

  • 读取联系电话范围在“1371811111”和“195324664654”之间的银行账户文档 
    db.accounts.find( {contact: {$elemMatch: {$gt:"1371811111", $lt: "195324664654"}}})
    
    { "_id" : ObjectId("5e1336e91f342ac67bb98e58"), "name" : "karen", "balance" : 3000, "contact" : [ "18391000411", "湖南省", "china" ] }
    { "_id" : ObjectId("5e1337dc1f342ac67bb98e5a"), "name" : "xiaowang", "balance" : 1500, "contact" : [ "18891000411", "湖南省", "china" ] }
    

正则表达式

  • 在和$in操作符一起使用时,只能使用/pattern/<options>
  • 读取用户姓名以k或者j开头的银行账户文档
    db.accounts.find({name: {$in : [/^k/, /^j/]}})
    
    { "_id" : ObjectId("5e1336e91f342ac67bb98e57"), "name" : "jack", "balance" : 2000, "contact" : [ "137111111", "陕西省", "China" ] }
    { "_id" : ObjectId("5e1336e91f342ac67bb98e58"), "name" : "karen", "balance" : 3000, "contact" : [ "18391000411", "湖南省", "china" ] }
    { "_id" : ObjectId("5e133b15738962fb118b2554"), "name" : "ke", "balance" : 1800, "contact" : [ [ "1754684641", "195324664654" ], "陕西省", "China" ] }
    

文档游标

  • db.collection.find()返回一个文档集合游标
  • 在不迭代游标的情况下,只列出前20个文档
  • var  myCour = db.accounts.find()
       myCour
     var myCourt = db.accounts.find()
    
    > myCourt
    
    { "_id" : ObjectId("5e1331591f342ac67bb98e52"), "name" : "xiaoke", "balance" : 1000 }
    { "_id" : ObjectId("5e1332d11f342ac67bb98e53"), "name" : "one", "balance" : 1000 }
    { "_id" : ObjectId("5e13331e1f342ac67bb98e54"), "name" : "one", "balance" : 1000 }
    { "_id" : ObjectId("5e1336e91f342ac67bb98e57"), "name" : "jack", "balance" : 2000, "contact" : [ "137111111", "陕西省", "China" ] }
    { "_id" : ObjectId("5e1336e91f342ac67bb98e58"), "name" : "karen", "balance" : 3000, "contact" : [ "18391000411", "湖南省", "china" ] }
    { "_id" : ObjectId("5e1337dc1f342ac67bb98e59"), "name" : "xiaoke", "balance" : 1000, "contact" : [ "1371811111", "山西省", "China" ] }
    { "_id" : ObjectId("5e1337dc1f342ac67bb98e5a"), "name" : "xiaowang", "balance" : 1500, "contact" : [ "18891000411", "湖南省", "china" ] }
    { "_id" : ObjectId("5e133b15738962fb118b2554"), "name" : "ke", "balance" : 1800, "contact" : [ [ "1754684641", "195324664654" ], "陕西省", "China" ] }
    
  • 我们也可以使用游标下标直接访问文档集合中的某一个文档
    var myCourt = db.accounts.find()
    
    > myCourt[1]
    
    {
    	"_id" : ObjectId("5e1332d11f342ac67bb98e53"),
    	"name" : "one",
    	"balance" : 1000
    }
    
  • 游历完游标中所有的文档之后,或者在10分钟之后,游标便会自动关闭。
  • 可以使用noCursorTimeout()函数来保持游标一直有效。
    var myCursor = db.accounts.find().noCursorTimeout()
    
    myCursor.close //关闭游标
  • 遍历所有文档游标
      方法一:
    var my = db.accounts.find({ name : "one"});
    
    > while( my.hasNext()){ printjson(my.next()) }
    
    {
        "_id" : ObjectId("5e1332d11f342ac67bb98e53"),
        "name" : "one",
        "balance" : 1000
    }
    {
        "_id" : ObjectId("5e13331e1f342ac67bb98e54"),
        "name" : "one",
        "balance" : 1000
    }

    方法二:

     var my = db.accounts.find({ name : "one"});
    
    
    > my.forEach(printjson)
    
    {
    	"_id" : ObjectId("5e1332d11f342ac67bb98e53"),
    	"name" : "one",
    	"balance" : 1000
    }
    {
    	"_id" : ObjectId("5e13331e1f342ac67bb98e54"),
    	"name" : "one",
    	"balance" : 1000
    }
  • cursor.limit(<number>)查询指定数量
    db.accounts.find().limit(3)
    
    { "_id" : ObjectId("5e1331591f342ac67bb98e52"), "name" : "xiaoke", "balance" : 1000 }
    { "_id" : ObjectId("5e1332d11f342ac67bb98e53"), "name" : "one", "balance" : 1000 }
    { "_id" : ObjectId("5e13331e1f342ac67bb98e54"), "name" : "one", "balance" : 1000 }
    

     find().limit(0)和find()结果一样。

  • cursor.skip(<offset>)绕过指定数量
    db.accounts.find().skip(3)
    
    { "_id" : ObjectId("5e1336e91f342ac67bb98e57"), "name" : "jack", "balance" : 2000, "contact" : [ "137111111", "陕西省", "China" ] }
    { "_id" : ObjectId("5e1336e91f342ac67bb98e58"), "name" : "karen", "balance" : 3000, "contact" : [ "18391000411", "湖南省", "china" ] }
    { "_id" : ObjectId("5e1337dc1f342ac67bb98e59"), "name" : "xiaoke", "balance" : 1000, "contact" : [ "1371811111", "山西省", "China" ] }
    { "_id" : ObjectId("5e1337dc1f342ac67bb98e5a"), "name" : "xiaowang", "balance" : 1500, "contact" : [ "18891000411", "湖南省", "china" ] }
    { "_id" : ObjectId("5e133b15738962fb118b2554"), "name" : "ke", "balance" : 1800, "contact" : [ [ "1754684641", "195324664654" ], "陕西省", "China" ] }
    
  • curor.count(<applySkipLimit>)
    默认情况下,<applySkipLimit>为false,既cursor.count()不会考虑cursor.skip()和cursor.limit()的效果
    db.accounts.find().limit(1).count()
    8
    > db.accounts.find().limit(1).count(true)
    1
    
  • cursor.sort(<document>)
    这里的<document>定义了排序的要求, 1表示由小及大的正向排序, -1 为逆向序
  • 按照余额从大到小,用户姓名按字母排序的方式排列银行账户文档
    db.accounts.find().sort({balance: -1, name: 1})
    
    { "_id" : ObjectId("5e1336e91f342ac67bb98e58"), "name" : "karen", "balance" : 3000, "contact" : [ "18391000411", "湖南省", "china" ] }
    { "_id" : ObjectId("5e1336e91f342ac67bb98e57"), "name" : "jack", "balance" : 2000, "contact" : [ "137111111", "陕西省", "China" ] }
    { "_id" : ObjectId("5e133b15738962fb118b2554"), "name" : "ke", "balance" : 1800, "contact" : [ [ "1754684641", "195324664654" ], "陕西省", "China" ] }
    { "_id" : ObjectId("5e1337dc1f342ac67bb98e5a"), "name" : "xiaowang", "balance" : 1500, "contact" : [ "18891000411", "湖南省", "china" ] }
    { "_id" : ObjectId("5e1332d11f342ac67bb98e53"), "name" : "one", "balance" : 1000 }
    { "_id" : ObjectId("5e13331e1f342ac67bb98e54"), "name" : "one", "balance" : 1000 }
    { "_id" : ObjectId("5e1331591f342ac67bb98e52"), "name" : "xiaoke", "balance" : 1000 }
    { "_id" : ObjectId("5e1337dc1f342ac67bb98e59"), "name" : "xiaoke", "balance" : 1000, "contact" : [ "1371811111", "山西省", "China" ] }
    
  • 读取余额最大的银行账户文档
    db.accounts.find().sort({balance:-1}).limit(1)
    
    { "_id" : ObjectId("5e1336e91f342ac67bb98e58"), "name" : "karen", "balance" : 3000, "contact" : [ "18391000411", "湖南省", "china" ] }
    
  • skip()在limit()之前执行
    db.accounts.find().limit(5).skip(3)
    
    { "_id" : ObjectId("5e1336e91f342ac67bb98e57"), "name" : "jack", "balance" : 2000, "contact" : [ "137111111", "陕西省", "China" ] }
    { "_id" : ObjectId("5e1336e91f342ac67bb98e58"), "name" : "karen", "balance" : 3000, "contact" : [ "18391000411", "湖南省", "china" ] }
    { "_id" : ObjectId("5e1337dc1f342ac67bb98e59"), "name" : "xiaoke", "balance" : 1000, "contact" : [ "1371811111", "山西省", "China" ] }
    { "_id" : ObjectId("5e1337dc1f342ac67bb98e5a"), "name" : "xiaowang", "balance" : 1500, "contact" : [ "18891000411", "湖南省", "china" ] }
    { "_id" : ObjectId("5e133b15738962fb118b2554"), "name" : "ke", "balance" : 1800, "contact" : [ [ "1754684641", "195324664654" ], "陕西省", "China" ] }
    
    db.accounts.find().skip(3).limit(5)
    
    { "_id" : ObjectId("5e1336e91f342ac67bb98e57"), "name" : "jack", "balance" : 2000, "contact" : [ "137111111", "陕西省", "China" ] }
    { "_id" : ObjectId("5e1336e91f342ac67bb98e58"), "name" : "karen", "balance" : 3000, "contact" : [ "18391000411", "湖南省", "china" ] }
    { "_id" : ObjectId("5e1337dc1f342ac67bb98e59"), "name" : "xiaoke", "balance" : 1000, "contact" : [ "1371811111", "山西省", "China" ] }
    { "_id" : ObjectId("5e1337dc1f342ac67bb98e5a"), "name" : "xiaowang", "balance" : 1500, "contact" : [ "18891000411", "湖南省", "china" ] }
    { "_id" : ObjectId("5e133b15738962fb118b2554"), "name" : "ke", "balance" : 1800, "contact" : [ [ "1754684641", "195324664654" ], "陕西省", "China" ] }
    
    
  • sort()在skip()和limit()之前执行
    db.accounts.find().sort({balance: -1 }).skip(3).limit(5)
    
    { "_id" : ObjectId("5e1336e91f342ac67bb98e58"), "name" : "karen", "balance" : 3000, "contact" : [ "18391000411", "湖南省", "china" ] }
    { "_id" : ObjectId("5e1336e91f342ac67bb98e57"), "name" : "jack", "balance" : 2000, "contact" : [ "137111111", "陕西省", "China" ] }
    { "_id" : ObjectId("5e133b15738962fb118b2554"), "name" : "ke", "balance" : 1800, "contact" : [ [ "1754684641", "195324664654" ], "陕西省", "China" ] }
    { "_id" : ObjectId("5e1337dc1f342ac67bb98e5a"), "name" : "xiaowang", "balance" : 1500, "contact" : [ "18891000411", "湖南省", "china" ] }
    { "_id" : ObjectId("5e1331591f342ac67bb98e52"), "name" : "xiaoke", "balance" : 1000 }
    
  • {field: inclusion} 1表示返回字段,0表示不返回字段
  • 只返回银行账户文档中的用户姓名(不返回文档主建)
    db.accounts.find({},{_id:0,name: 1})
    
    { "name" : "xiaoke" }
    { "name" : "one" }
    { "name" : "one" }
    { "name" : "jack" }
    { "name" : "karen" }
    { "name" : "xiaoke" }
    { "name" : "xiaowang" }
    { "name" : "ke" }
    { "name" : "xin" }
    { "name" : "xin" }
    { "name" : "xinzai" }
    { "name" : "xinge" }
    { "name" : "nanzai" }
    
  • 不返回银行账户文档中的用户姓名(也不返回文档主键)
    db.accounts.find({},{name:0,_id: 0})
    
    { "balance" : 1000 }
    { "balance" : 1000 }
    { "balance" : 1000 }
    { "balance" : 2000, "contact" : [ "137111111", "陕西省", "China" ] }
    { "balance" : 3000, "contact" : [ "18391000411", "湖南省", "china" ] }
    { "balance" : 1000, "contact" : [ "1371811111", "山西省", "China" ] }
    { "balance" : 1500, "contact" : [ "18891000411", "湖南省", "china" ] }
    { "balance" : 1800, "contact" : [ [ "1754684641", "195324664654" ], "陕西省", "China" ] }
    { "balance" : 5000, "contact" : [ "1204557644", "广东省", "china" ] }
    { "balance" : 5000, "contact" : [ "1204557644", "广东省", "china" ] }
    { "balance" : 500 }
    { "balance" : 600 }
    { "balance" : 3500 }
    
  • 除了_id以外,只能查询所有返回、或者所有不返回的结果、不能两者同时查询
    db.accounts.find({},{name:0,_id: 0, balance: 1})
    
    Error: error: {
    	"ok" : 0,
    	"errmsg" : "Projection cannot have a mix of inclusion and exclusion.",
    	"code" : 2,
    	"codeName" : "BadValue"
    }
    
  • (有疑问,为什么我的$slide的值被解析成double了)$slice操作符可以返回数组字段中的部分元素()
    db.accounts.find({},{_id: 0 , name:1, contact: { $slide: 2}})
    
    Error: error: {
    	"ok" : 0,
    	"errmsg" : "Unsupported projection option: contact: { $slide: 2.0 }",
    	"code" : 2,
    	"codeName" : "BadValue"
    }
    
  • $elemMatch和$操作符可以返回数组字段中满足筛选条件的第一个元素
    db.accounts.find({},{_id: 0 , name:1, contact: { $elemMatch:{$gt: "湖南省"}}})
    
    { "name" : "xiaoke" }
    { "name" : "one" }
    { "name" : "one" }
    { "name" : "jack", "contact" : [ "陕西省" ] }
    { "name" : "karen" }
    { "name" : "xiaoke" }
    { "name" : "xiaowang" }
    { "name" : "ke", "contact" : [ "陕西省" ] }
    { "name" : "xin" }
    { "name" : "xin" }
    { "name" : "xinzai" }
    { "name" : "xinge" }
    { "name" : "nanzai" }
    

更新文档

  • db.collection.update()
  • db.<collection>.update(<query>, <update>, <options>)
    <query>文档定义了更新操作时筛选文档的条件
    <update>文档提供了更新的内容
    <options>文档声明了一些更新操作的参数
  • 如果<update>文档不包含任何更新操作符,db.collection.update()将会使用<update>文档直接替换集合中符合<qurey>文档筛选条件的文档
  • 将jack的账户余额更改为“1950” (<update>中必须带name,负责就会改空)
    db.accounts.update({name:"jack"},{name:"jack",balance:1950})
    
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
    
  • 任何情况下_id字段不会被更改

  • 在使用<update>文档替换整篇被更新文档时,只有第一篇符合<query>文档筛选条件的文档会被更新

  • 查看余额在1000到1900之间的账户文档

    b.accounts.update({balance:{$gt:1000, $lt:1900}}, {name:"bill", balance:1700, gender: "M"})
    //update条件有多个结果,只有第一篇文档被更新
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
    
  • 文档更新操作符
    $set   更新或新增字段
    $unset 删除字段
    $rename 重命名字段
    $inc  加减字段值
    $mul 想乘字段值
    $min 比较减小字段值
    $max 比较增大字段值

  • $set操作符

  • 更新karen的开户余额和信息。

    db.accounts.update({name:"karen"},{$set: {balance:2500, info:{ dateOpened: new Date("2020-1-9 15:05:05"), branch: "branch1"}}})
    
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
    
    > db.accounts.find({name: "karen"}).pretty()
    
    {
    	"_id" : ObjectId("5e1336e91f342ac67bb98e58"),
    	"name" : "karen",
    	"balance" : 2500,
    	"contact" : [
    		"18391000411",
    		"湖南省",
    		"china"
    	],
    	"info" : {
    		"dateOpened" : ISODate("2020-01-09T15:05:05Z"),
    		"branch" : "branch1"
    	}
    }
    
  • 更新karen的银行账户的开户时间(更新内嵌文档的字段)

    db.accounts.update({name:"jack"},{$set:{ "info.dateOpened":new Date("2029-9-9 15:05:05")}})
    
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
    
  • 更新karen账户信息中的电话号码

     db.accounts.update({name:"karen"},{$set:{ "contact.0": "1777777777777"}})
    
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
    
    > db.accounts.find({name: "karen"}).pretty()
    
    {
    	"_id" : ObjectId("5e1336e91f342ac67bb98e58"),
    	"name" : "karen",
    	"balance" : 2500,
    	"contact" : [
    		"1777777777777",
    		"湖南省",
    		"china"
    	],
    	"info" : {
    		"dateOpened" : ISODate("2020-01-09T15:05:05Z"),
    		"branch" : "branch1"
    	}
    }
    

    1

  • $set更新的相同条件的文档,只会更改第一个
     

    db.accounts.update({name: "one"}, {$set: { "balance" : 500}})
    
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
    
    > db.accounts.find()
     //只将name为one的第一个balance余额修改了 
    { "_id" : ObjectId("5e1331591f342ac67bb98e52"), "name" : "xiaoke", "balance" : 1000 }
    { "_id" : ObjectId("5e1332d11f342ac67bb98e53"), "name" : "one", "balance" : 500 }
    { "_id" : ObjectId("5e13331e1f342ac67bb98e54"), "name" : "one", "balance" : 1000 }
    { "_id" : ObjectId("5e1336e91f342ac67bb98e57"), "info" : "jack", "contact" : { "0" : "1777777777777" } }
    { "_id" : ObjectId("5e1336e91f342ac67bb98e58"), "name" : "karen" }
    { "_id" : ObjectId("5e1337dc1f342ac67bb98e59"), "name" : "xiaoke", "balance" : 1000, "contact" : [ "1371811111", "山西省", "China" ] }
    { "_id" : ObjectId("5e1337dc1f342ac67bb98e5a"), "name" : "bill", "balance" : 1700, "gender" : "M" }
    { "_id" : ObjectId("5e133b15738962fb118b2554"), "name" : "ke", "balance" : 1800, "contact" : [ [ "1754684641", "195324664654" ], "陕西省", "China" ] }
    { "_id" : ObjectId("5e154a6d297892ae4951650d"), "name" : "kx", "balance" : 5000, "contact" : [ "1204557644", "广东省", "china" ] }
    { "_id" : ObjectId("5e154a79297892ae4951650e"), "name" : "xin", "balance" : 5000, "contact" : [ "1204557644", "广东省", "china" ] }
    { "_id" : ObjectId("5e1576cc665014c2c50ea536"), "name" : "xinzai", "balance" : 500 }
    { "_id" : ObjectId("5e1576cc665014c2c50ea537"), "name" : "xinge", "balance" : 600 }
    { "_id" : ObjectId("5e157856665014c2c50ea538"), "name" : "nanzai", "balance" : 3500 }
    
  • 添加jack的联系方式(如果向现有数组字段范围以外的位置添加新值,数组字段的长度就会扩大,未被复制的数组成员将被设置为null)

    db.accounts.update({name: "karen"},{$set:{"contact.4": "new contact4"}})
    
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
    
    > db.accounts.find({name: "karen"}).pretty()
    
    {
    	"_id" : ObjectId("5e1336e91f342ac67bb98e58"),
    	"name" : "karen",
    	"balance" : 2500,
    	"contact" : [
    		"1777777777777",
    		"湖南省",
    		"china",
    		null,
    		"new contact4"
    	],
    	"info" : {
    		"dateOpened" : ISODate("2020-01-09T15:05:05Z"),
    		"branch" : "branch1"
    	}
    }
    

     
     

  • 删除字段 $unset

  • 删除karen的银行账户余额和开户地点
     

    db.accounts.update({name: "karen"}, {$unset: {balance:"", "info.branch": ""}})
    
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
    
    > db.accounts.find({name: "karen"}).pretty()
    
    {
    	"_id" : ObjectId("5e1336e91f342ac67bb98e58"),
    	"name" : "karen",
    	"contact" : [
    		"1777777777777",
    		"湖南省",
    		"china",
    		null,
    		"new contact4"
    	],
    	"info" : {
    		"dateOpened" : ISODate("2020-01-09T15:05:05Z")
    	}
    }
    

    说明:$unset命令中的赋值("")对操作结果并没有任何影响。既里面填写与空着都会删除该字段。

  • 删除数组内的字段$unset

  • 删除jack的联系电话

    db.accounts.update({name:"karen"}, {$unset: {"contact.0":""}})
    
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
    
    > db.accounts.find({name: "karen"}).pretty()
    
    {
    	"_id" : ObjectId("5e1336e91f342ac67bb98e58"),
    	"name" : "karen",
    	"contact" : [
    		null,
    		"湖南省",
    		"china",
    		null,
    		"new contact4"
    	],
    	"info" : {
    		"dateOpened" : ISODate("2020-01-09T15:05:05Z")
    	}
    }
    

    说明:当时用$unset命令删除数组字段中的某一个元素时,这个元素不会被删除,只会被赋值null值,而数组的长度不会改变。

  • 重命名字段$rename
    说明:如果$rename命令要重命名的字段并不存在,那么文档内容不被改变
     

    db.accounts.update({name: "karen"},{$rename:{"notExist": "notExist"}})
    WriteResult({
    	"nMatched" : 0,
    	"nUpserted" : 0,
    	"nModified" : 0,
    	"writeError" : {
    		"code" : 2,
    		"errmsg" : "The source and target field for $rename must differ: notExist: \"notExist\""
    	}
    })
  • 如果新的字段名已经存在,那么原有的这个字段就会被覆盖掉。

    // 查看name为jack
    db.accounts.find({name:"jack"}).pretty()
    {
    	"_id" : ObjectId("5e1336e91f342ac67bb98e57"),
    	"name" : "jack",
    	"info" : {
    		"dateOpened" : ISODate("2029-09-09T15:05:05Z")
    	},
    	"contact" : {
    		"0" : "1777777777777"
    	}
    }
    
    
    // 重命名字段name 为info
    db.accounts.update({name:"jack"}, {$rename: {name:"info"}})
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
    
    //查看info为jack, 原来的info被覆盖掉了
    db.accounts.find({info:"jack"}).pretty()
    {
    	"_id" : ObjectId("5e1336e91f342ac67bb98e57"),
    	"info" : "jack",
    	"contact" : {
    		"0" : "1777777777777"
    	}
    }
    

    说明:当$rename命令中的新字段存在的时候,$rename命令会先$unset新旧字段,然后在$set新字段

  • 更新kx的银行账户的开户时间和联系方式
     

    db.accounts.update({name: "kx"}, {$set:{info:{ dateOpene: new Date("2020年1月9日17:55:38"), branch: "branch1"}, "contact.3":{ primaryEmail: "[email protected]", secondaryEmail: "[email protected]"} }})
    
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
    
    
    db.accounts.find({name: "kx"}).pretty()
    
    {
    	"_id" : ObjectId("5e154a6d297892ae4951650d"),
    	"name" : "kx",
    	"balance" : 5000,
    	"contact" : [
    		"1204557644",
    		"广东省",
    		"china",
    		{
    			"primaryEmail" : "[email protected]",
    			"secondaryEmail" : "[email protected]"
    		}
    	],
    	"info" : {
    		"dateOpene" : ISODate("1970-01-01T00:00:00Z"),
    		"branch" : "branch1"
    	}
    }
    
  • 更改kx的联系方式 (重命名数组中内嵌文档的字段)

  • 更新账户余额和开户地点字段在文档中的位置

    db.accounts.update({name: "kx"}, { $rename : {"info.dateOpene" : "date", "branch" : "branch2"}})
    
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
    
    db.accounts.find({name : "kx"}).pretty()
    
    {
    	"_id" : ObjectId("5e154a6d297892ae4951650d"),
    	"name" : "kx",
    	"balance" : 5000,
    	"contact" : [
    		[
    			"44444",
    			"55555"
    		],
    		"广东省",
    		"china",
    		{
    			"primaryEmail" : "[email protected]",
    			"secondaryEmail" : "[email protected]"
    		}
    	],
    	"info" : {
    		"branch" : "branch1"
    	},
    	"date" : ISODate("1970-01-01T00:00:00Z")
    }
  • $rename命令中的旧字段和新字段都不可以指向数组元素

    db.accounts.update({name: "kx"}, {$rename: {"contact.3.primaryEmail" : "email"}})
    
    WriteResult({
    	"nMatched" : 0,
    	"nUpserted" : 0,
    	"nModified" : 0,
    	"writeError" : {
    		"code" : 2,
    		"errmsg" : "The source field cannot be an array element, 'contact.3.primaryEmail' in doc with _id: ObjectId('5e154a6d297892ae4951650d') has an array field called 'contact'"
    	}
    })
  • $rename命令中的就自断和新字段都不可以指向数组元素
    这一点和之前介绍过的$set和$unset命令不同
     

    db.accounts.find({name : "kx"}).pretty()
    {
    	"_id" : ObjectId("5e154a6d297892ae4951650d"),
    	"name" : "kx",
    	"balance" : 5000,
    	"contact" : [
    		[
    			"44444",
    			"55555"
    		],
    		"广东省",
    		"china",
    		{
    			"primaryEmail" : "[email protected]",
    			"secondaryEmail" : "[email protected]"
    		}
    	],
    	"info" : {
    		"branch" : "branch1"
    	},
    	"date" : ISODate("1970-01-01T00:00:00Z")
    }
    > db.accounts.update({name:"kx"}, {$rename : {"branch": "contact.3.aa"}})
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 0 })
    > db.accounts.update({name:"kx"}, {$rename : {"branch": "contact.3.secondaryEmail"}})
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 0 })
    
    //实际一点都没有改变
    > db.accounts.find({name : "kx"}).pretty()
    {
    	"_id" : ObjectId("5e154a6d297892ae4951650d"),
    	"name" : "kx",
    	"balance" : 5000,
    	"contact" : [
    		[
    			"44444",
    			"55555"
    		],
    		"广东省",
    		"china",
    		{
    			"primaryEmail" : "[email protected]",
    			"secondaryEmail" : "[email protected]"
    		}
    	],
    	"info" : {
    		"branch" : "branch1"
    	},
    	"date" : ISODate("1970-01-01T00:00:00Z")
    }
  • 加 乘 操作符 $inc 、$mul

  • 查看david的银行账户文档

    db.accounts.find({name : "david"})
    
    { "_id" : ObjectId("5e18592d49c9a0cf0c03948f"), "name" : "david", "balance" : 200 }
    
  • 更新david的账户余额($inc 在原来的余额基础上加上-0.5)

    db.accounts.update({name: "david"}, {$inc: {balance: -0.5}})
    
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
    
    > db.accounts.find({name : "david"})
    
    { "_id" : ObjectId("5e18592d49c9a0cf0c03948f"), "name" : "david", "balance" : 199.5 }
    
  • 更新david的账户余额($mul在原来的余额基础上乘以0.5)

    db.accounts.find({name : "david"})
    { "_id" : ObjectId("5e18592d49c9a0cf0c03948f"), "name" : "david", "balance" : 200 }
    > db.accounts.update({name: "david"}, {$mul: {balance: 0.5}})
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
    > db.accounts.find({name : "david"})
    { "_id" : ObjectId("5e18592d49c9a0cf0c03948f"), "name" : "david", "balance" : 100 }

    说明:$inc和$mul命令只能应用在数字字段上

  • 比较大小操作符 $min  $max

  • 更新karen的账户余额
    说明:$min 和$max操作符会和原来的数据先做比较,如果元数据符合条件则不更新,如果不符合,则更新。

    db.accounts.update({name: "kx"}, {$max: {balance: 6000}})
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
    
    > db.accounts.find({name : "kx"})
    
    { "_id" : ObjectId("5e154a6d297892ae4951650d"), "name" : "kx", "balance" : 6000, "contact" : [ [ "44444", "55555" ], "广东省", "china", { "primaryEmail" : "[email protected]", "secondaryEmail" : "[email protected]" } ], "info" : { "branch" : "branch1" }, "date" : ISODate("1970-01-01T00:00:00Z") }
    
    > db.accounts.update({name: "kx"}, {$max: {balance: 5000}})
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 0 })
    
  • 如果被更新的值不存在,则会添加上去

    db.accounts.find({name : "kx"})
    { "_id" : ObjectId("5e154a6d297892ae4951650d"), "name" : "kx", "balance" : 6000, "contact" : [ [ "44444", "55555" ], "广东省", "china", { "primaryEmail" : "[email protected]", "secondaryEmail" : "[email protected]" } ], "info" : { "branch" : "branch1" }, "date" : ISODate("1970-01-01T00:00:00Z") }
    
    //用$max更新没有的字段上去
    db.accounts.update({name: "kx"}, {$max: {money: 5000}})
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
    
    db.accounts.find({name: "kx"})
    { "_id" : ObjectId("5e154a6d297892ae4951650d"), "name" : "kx", "balance" : 6000, "contact" : [ [ "44444", "55555" ], "广东省", "china", { "primaryEmail" : "[email protected]", "secondaryEmail" : "[email protected]" } ], "info" : { "branch" : "branch1" }, "date" : ISODate("1970-01-01T00:00:00Z"), "money" : 5000 }
    
    
    
  • 如果被更新的字段值类型不一致,只要符合比较条件,也会被更新上去。

    db.accounts.update({name: "kx"}, {$max: {money: "aaa"}})
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
    
    db.accounts.update({name: "kx"}, {$min: {money: null}})
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
    
    db.accounts.update({name: "kx"}, {$max: {money: 2000}})
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
    
  • 数组更新操作符$addToSet

  • 向kx的账户文档中添加联系方式

    db.accounts.find({name : "kx"}).pretty()
    {
    	"_id" : ObjectId("5e154a6d297892ae4951650d"),
    	"name" : "kx",
    	"balance" : 6000,
    	"contact" : [
    		[
    			"44444",
    			"55555"
    		],
    		"广东省",
    		"china",
    		{
    			"primaryEmail" : "[email protected]",
    			"secondaryEmail" : "[email protected]"
    		}
    	],
    	"info" : {
    		"branch" : "branch1"
    	},
    	"date" : ISODate("1970-01-01T00:00:00Z"),
    	"money" : 2000
    }
    
    > db.accounts.update({name: "kx"}, {$addToSet : { contact : "new ziduan" } })
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
    > db.accounts.find({name : "kx"}).pretty()
    {
    	"_id" : ObjectId("5e154a6d297892ae4951650d"),
    	"name" : "kx",
    	"balance" : 6000,
    	"contact" : [
    		[
    			"44444",
    			"55555"
    		],
    		"广东省",
    		"china",
    		{
    			"primaryEmail" : "[email protected]",
    			"secondaryEmail" : "[email protected]"
    		},
    		"new ziduan"
    	],
    	"info" : {
    		"branch" : "branch1"
    	},
    	"date" : ISODate("1970-01-01T00:00:00Z"),
    	"money" : 2000
    }
    
  • 当向数组中添加重复的值,是不会成功的。

    db.accounts.update({name: "kx"}, {$addToSet : { contact : "new ziduan" } })
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 0 })
    
  • 向kx的账户文档中添加新的联系方式

    db.accounts.find({name : "kx"}).pretty()
    {
    	"_id" : ObjectId("5e154a6d297892ae4951650d"),
    	"name" : "kx",
    	"balance" : 6000,
    	"contact" : [
    		[
    			"44444",
    			"55555"
    		],
    		"广东省",
    		"china",
    		{
    			"primaryEmail" : "[email protected]",
    			"secondaryEmail" : "[email protected]"
    		},
    		"new ziduan"
    	],
    	"info" : {
    		"branch" : "branch1"
    	},
    	"date" : ISODate("1970-01-01T00:00:00Z"),
    	"money" : 2000
    }
    
    //更新
    > db.accounts.update({name: "kx"}, {$addToSet : { contact : {secondaryEmail: "[email protected]", "primaryEmail" : "[email protected]"} } })
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
    
    
    > db.accounts.find({name : "kx"}).pretty()
    {
    	"_id" : ObjectId("5e154a6d297892ae4951650d"),
    	"name" : "kx",
    	"balance" : 6000,
    	"contact" : [
    		[
    			"44444",
    			"55555"
    		],
    		"广东省",
    		"china",
    		{
    			"primaryEmail" : "[email protected]",
    			"secondaryEmail" : "[email protected]"
    		},
    		"new ziduan",
    		{
    			"secondaryEmail" : "[email protected]",
    			"primaryEmail" : "[email protected]"
    		}
    	],
    	"info" : {
    		"branch" : "branch1"
    	},
    	"date" : ISODate("1970-01-01T00:00:00Z"),
    	"money" : 2000
    }
    
  • 向kx的账户文档中添加多个联系方式
    $addToSet会将数组插入被更新的数组字段中,成为内嵌数组。

    db.accounts.update({name: "kx"}, {$addToSet: {contact: ["contact1", "contact1"]}})
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
    
    > db.accounts.find({name : "kx"}).pretty()
    {
    	"_id" : ObjectId("5e154a6d297892ae4951650d"),
    	"name" : "kx",
    	"balance" : 6000,
    	"contact" : [
    		[
    			"44444",
    			"55555"
    		],
    		"广东省",
    		"china",
    		{
    			"primaryEmail" : "[email protected]",
    			"secondaryEmail" : "[email protected]"
    		},
    		"new ziduan",
    		{
    			"secondaryEmail" : "[email protected]",
    			"primaryEmail" : "[email protected]"
    		},
    		[
    			"contact1",
    			"contact1"
    		]
    	],
    	"info" : {
    		"branch" : "branch1"
    	},
    	"date" : ISODate("1970-01-01T00:00:00Z"),
    	"money" : 2000
    }
    
  • 如果想要将多个元素直接添加到数组字段中,则需要使用$each操作符。
     

    db.accounts.update({name: "kx"}, {$addToSet: {contact: {$each: ["contact1", "contact2"]} }})
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
    
    //一次性加入了两个元素
    > db.accounts.find({name : "kx"}).pretty()
    {
    	"_id" : ObjectId("5e154a6d297892ae4951650d"),
    	"name" : "kx",
    	"balance" : 6000,
    	"contact" : [
    		[
    			"44444",
    			"55555"
    		],
    		"广东省",
    		"china",
    		{
    			"primaryEmail" : "[email protected]",
    			"secondaryEmail" : "[email protected]"
    		},
    		"new ziduan",
    		{
    			"secondaryEmail" : "[email protected]",
    			"primaryEmail" : "[email protected]"
    		},
    		[
    			"contact1",
    			"contact1"
    		],
    		"contact1",
    		"contact2"
    	],
    	"info" : {
    		"branch" : "branch1"
    	},
    	"date" : ISODate("1970-01-01T00:00:00Z"),
    	"money" : 2000
    }
    
  • 数组中删除元素$pop

  • 从kx的账户文档中删除最后一个联系方式

     db.accounts.update({name: "kx"}, {$pop: {contact: 1}})
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
    
    //把contact数组中最后中一个元素删除了
    > db.accounts.find({name : "kx"}).pretty()
    {
    	"_id" : ObjectId("5e154a6d297892ae4951650d"),
    	"name" : "kx",
    	"balance" : 6000,
    	"contact" : [
    		[
    			"44444",
    			"55555"
    		],
    		"广东省",
    		"china",
    		{
    			"primaryEmail" : "[email protected]",
    			"secondaryEmail" : "[email protected]"
    		},
    		"new ziduan",
    		{
    			"secondaryEmail" : "[email protected]",
    			"primaryEmail" : "[email protected]"
    		},
    		[
    			"contact1",
    			"contact1"
    		],
    		"contact1"
    	],
    	"info" : {
    		"branch" : "branch1"
    	},
    	"date" : ISODate("1970-01-01T00:00:00Z"),
    	"money" : 2000
    }
  • 删除双重数组中的元素
db.accounts.update({name : "kx"}, {$pop : {"contact.6" : -1}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

//删除了数组contact 中第7个元素中的第一个
> db.accounts.find({name : "kx"}).pretty()
{
	"_id" : ObjectId("5e154a6d297892ae4951650d"),
	"name" : "kx",
	"balance" : 6000,
	"contact" : [
		[
			"44444",
			"55555"
		],
		"广东省",
		"china",
		{
			"primaryEmail" : "[email protected]",
			"secondaryEmail" : "[email protected]"
		},
		"new ziduan",
		{
			"secondaryEmail" : "[email protected]",
			"primaryEmail" : "[email protected]"
		},
		[
			"contact1"
		],
		"contact1"
	],
	"info" : {
		"branch" : "branch1"
	},
	"date" : ISODate("1970-01-01T00:00:00Z"),
	"money" : 2000
}
  • 删除掉数组中最后一个元素后,会留下空数组
    注意:$pop操作符只能应用在数组字段上,应用在非数组上就会出错。

    db.accounts.update({name : "kx"}, {$pop : {"contact.6" : -1}})
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
    
    > db.accounts.find({name : "kx"}).pretty()
    {
    	"_id" : ObjectId("5e154a6d297892ae4951650d"),
    	"name" : "kx",
    	"balance" : 6000,
    	"contact" : [
    		[
    			"44444",
    			"55555"
    		],
    		"广东省",
    		"china",
    		{
    			"primaryEmail" : "[email protected]",
    			"secondaryEmail" : "[email protected]"
    		},
    		"new ziduan",
    		{
    			"secondaryEmail" : "[email protected]",
    			"primaryEmail" : "[email protected]"
    		},
    		[ ],
    		"contact1"
    	],
    	"info" : {
    		"branch" : "branch1"
    	},
    	"date" : ISODate("1970-01-01T00:00:00Z"),
    	"money" : 2000
    }
    
  • 将ke的账户文档复制为lawrence的账户文档

    db.accounts.find({name: "ke"})
    { "_id" : ObjectId("5e133b15738962fb118b2554"), "name" : "ke", "balance" : 1800, "contact" : [ [ "1754684641", "195324664654" ], "陕西省", "China" ] }
    
    // 开始复制
    > db.accounts.find({name: "ke"},{_id: 0}).forEach(function(doc){ var newDoc = doc;  newDoc.name = "lawrence"; db.accounts.insert(newDoc); })
    
    { "_id" : ObjectId("5e186ccb49c9a0cf0c039491"), "name" : "lawrence", "balance" : 1800, "contact" : [ [ "1754684641", "195324664654" ], "陕西省", "China" ] }
    
    
  • $pull 删除数组中指定位置的元素

  • 从lawrence的联系方式中,删去数组contact 中包含"664"字母的元素

    db.accounts.find({name : "lawrence"})
    { "_id" : ObjectId("5e186ccb49c9a0cf0c039491"), "name" : "lawrence", "balance" : 1800, "contact" : [ [ "1754684641", "195324664654" ], "陕西省", "China" ] }
    
    //删除了 china
    > db.accounts.update({name: "lawrence"}, {$pull : {"contact": {$regex : /in/}}})
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
    > db.accounts.find({name : "lawrence"})
    { "_id" : ObjectId("5e186ccb49c9a0cf0c039491"), "name" : "lawrence", "balance" : 1800, "contact" : [ [ "1754684641", "195324664654" ], "陕西省" ] }
    
  • 从lawrence的联系方式中,删除联系电话号码包含“1754684641”的数组

    { "_id" : ObjectId("5e186ccb49c9a0cf0c039491"), "name" : "lawrence", "balance" : 1800, "contact" : [ [ "1754684641", "195324664654" ], "陕西省" ] }
    
    //删除了包含"1754684641"的数组
    > db.accounts.update({name: "lawrence"}, {$pull : {"contact": {$elemMatch : {$eq: "1754684641"}}}})
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
    
    > db.accounts.find({name : "lawrence"})
    { "_id" : ObjectId("5e186ccb49c9a0cf0c039491"), "name" : "lawrence", "balance" : 1800, "contact" : [ "陕西省" ] }
    
  • $pull命令会山区包含指定的文档字段和字段值的文档元素,字段排列顺序不需要完全匹配

    db.account.update({name: "小六"}, {$pull : {contact: {"aaa" : "ccom"}}})
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
    
    > db.account.find({name: "小六"})
    { "_id" : ObjectId("5e1f14d742045a554e10c29c"), "name" : "小六", "balance" : 650, "contact" : [ [ 9800, 998888 ], "西安市", "陕西省" ] }
    
  • $pullAll必须删除一个完整的数组

    db.account.update({name: "小六"}, {$pullAll : {"contact" : [ [ 9800, 998888 ], "西安市", "陕西省", { "email" : "[email protected]", "secondemail" : "[email protected]" } ]}})
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
    
    > db.account.find({name: "小六"})
    { "_id" : ObjectId("5e1f14d742045a554e10c29c"), "name" : "小六", "balance" : 650, "contact" : [ ] }
    
  • 向数组字段中添加元素$push

  • $push和$addToSet命令相似,但是$push命令的功能更强大

  • 和$addToSet命令一样,如果$push命令中指定的数组字段不存在,这个字段会被添加到文档中

    db.account.update({name:"lawrence"}, {$push: {newArray : "new element"}})
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
    > db.account.find({name: "lawrence"})
    { "_id" : ObjectId("5e1f0df242045a554e10c294"), "name" : "lawrence", "balance" : 500, "newArray" : [ "new element" ] }
    
  • $set、".$"更新数组中符合条件的第一个元素

    db.account.find({name : "小九"})
    { "_id" : ObjectId("5e1f1bb742045a554e10c29f"), "name" : "小九", "newArray" : [ "push41", "push2", "push3", "push4" ] }
    
    
    db.account.update({name: "小九", newArray: "push3"}, {$set : { "newArray.$": "updated"} })
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
    
    > db.account.find({name: "小九"})
    { "_id" : ObjectId("5e1f1bb742045a554e10c29f"), "name" : "小九", "newArray" : [ "push41", "push2", "updated", "push4" ] }
  • $set、".$[]"更新数组中所有元素

    db.account.find({name: "小五"})
    { "_id" : ObjectId("5e1f102142045a554e10c299"), "name" : "小五", "balance" : 650, "contact" : [ [ 558800, 7788 ], "西安市", "陕西省" ] }
    
    
    db.account.update({name: "小五"}, {$set: {"contact.0.$[]": "888888" }})
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
    
    
    db.account.find({name: "小五"})
    { "_id" : ObjectId("5e1f102142045a554e10c299"), "name" : "小五", "balance" : 650, "contact" : [ [ "888888", "888888" ], "西安市", "陕西省" ] }
    
  • update命令中使用的筛选条件只对应于一篇文档,及时刷选条件对应多篇文档,update命令仍然只会更新一篇文档

  • multi更新多个文档

    db.account.update({},{$set:{balance: 650}}, {multi: true})
    WriteResult({ "nMatched" : 16, "nUpserted" : 0, "nModified" : 9 })
    
  • MongoDB只能保证单个文档操作的原子性,不能保证多个文档操作的原子性。

  • 更新多个文档的操作虽然在单一线程中执行,但是线程在执行过程中可能被挂起,以便其他线程也有机会对数据进行操作。

删除文档

  • db.<collection>.remove(<query>, <options>)
    <options>文档声明了一些删除操作的参数
    db.account.remove({balance: 800})
    WriteResult({ "nRemoved" : 3 })
    
  • 在默认情况下,remove会删除所有符合条件的文档
  • 如果只想删除满足筛选条件的第一篇文档,可以使用justOne选项
  • 删除一篇小于100的账户文档
    db.account.remove({balance: 650},{justOne: true})
    WriteResult({ "nRemoved" : 1 })
    
  • 删除集合drop
  • remove命令可以删除集合内的所有文档,但是不会删除集合
    db.lianxi.find()
    { "_id" : ObjectId("5e20371bb79fceaf9ea4be8d"), "name" : "小一", "contact" : [ [ "00000", "777777" ], "西安", "陕西省" ], "balance" : 500 }
    
    //不会删除集合,只会删除数据
    > db.lianxi.remove({balance: 500})
    WriteResult({ "nRemoved" : 1 })
    
    > show collections
      lianxi
    
    
    
    db.lianxi.find()
    { "_id" : ObjectId("5e203765b79fceaf9ea4be8e"), "name" : "小一", "contact" : [ [ "00000", "777777" ], "西安", "陕西省" ], "balance" : 500 }
    
    //会把集合删除掉
    > db.lianxi.drop()
    true
    
    show collections//空的
    
    
  • 如果集合中的文档数据很多,使用remove命令删除所有文档的效率不高,更加有效率的方法:使用drop命令删除集合,然后再创建空集合并创建索引。
  • (未理解)对银行账户文档进行重新投影$project ()
    db.account.insertMany([{name:{firstName:"alice", lastName: "wang"},balance:500},{name:{firstName:"bob", lastName: "yang"},balance:400}])
    {
    	"acknowledged" : true,
    	"insertedIds" : [
    		ObjectId("5e204079b79fceaf9ea4be8f"),
    		ObjectId("5e204079b79fceaf9ea4be90")
    	]
    }
    
    db.account.aggregate([{$project:{_id:0, balance:1, clientName: "$name.firstName"}}])
    { "balance" : 500, "clientName" : "alice" }
    { "balance" : 400, "clientName" : "bob" }
    
    
     
    db.account.aggregate([{$project:{_id:0, balance:1, nameArray: ["$name.firstName", "$name.middleName", "$name.lastName"]}}])
    
    { "balance" : 500, "nameArray" : [ "alice", null, "wang" ] }
    { "balance" : 400, "nameArray" : [ "bob", null, "yang" ] }
    


     

聚合管道

  • (待理解)$project是一个很常用的聚合阶段,可以用来灵活的控制输出文档的格式,也可以用来剔除不相关的字段,已优化聚合管道操作的性能。

  • 对银行账户文档进行筛选$match

    db.account.aggregate([{$match:{"name.firstName": "alice"}}])
    { "_id" : ObjectId("5e204079b79fceaf9ea4be8f"), "name" : { "firstName" : "alice", "lastName" : "wang" }, "balance" : 500 }
    
    
    
    db.account.aggregate([{$match:{$or:[{balance: {$gt:390, $lt:410}}, {"name.lastName": "yang"}]}}])
    { "_id" : ObjectId("5e204079b79fceaf9ea4be90"), "name" : { "firstName" : "bob", "lastName" : "yang" }, "balance" : 400 }
    
    
    
    db.account.aggregate([{$match:{$or:[{balance: {$gt:390, $lt:410}}, {"name.lastName": "yang"}]}}, {$project: { _id : 0}}])
    { "name" : { "firstName" : "bob", "lastName" : "yang" }, "balance" : 400 }
    
  • $limit和$skip 

  • 筛选第一篇银行账户文档

    db.account.aggregate([{$limit:1}])
    { "_id" : ObjectId("5e2035cab79fceaf9ea4be88"), "name" : "小柯", "contact" : [ "11702908819" ] }
    
  • 调过第一篇银行账户文档

    db.account.aggregate([{$skip:1}])
    { "_id" : ObjectId("5e203605b79fceaf9ea4be89"), "name" : "小一", "contact" : [ "11702908819", "西安", "陕西省" ] }
    { "_id" : ObjectId("5e203630b79fceaf9ea4be8a"), "name" : "小一", "contact" : [ [ "00000", "777777" ], "西安", "陕西省" ] }
    { "_id" : ObjectId("5e20366cb79fceaf9ea4be8b"), "name" : "小一", "contact" : [ [ "00000", "777777" ], "西安", "陕西省" ], "ke" : { "aa" : "bb", "cc" : "dd" } }
    { "_id" : ObjectId("5e203689b79fceaf9ea4be8c"), "name" : "小一", "contact" : [ [ "00000", "777777" ], "西安", "陕西省" ], "balance" : 500 }
    { "_id" : ObjectId("5e204079b79fceaf9ea4be8f"), "name" : { "firstName" : "alice", "lastName" : "wang" }, "balance" : 500 }
    { "_id" : ObjectId("5e204079b79fceaf9ea4be90"), "name" : { "firstName" : "bob", "lastName" : "yang" }, "balance" : 400 }
    
  • 将文档中的货币种类数组展开

    db.account.find({"name.firstName": "alice"})
    { "_id" : ObjectId("5e204079b79fceaf9ea4be8f"), "name" : { "firstName" : "alice", "lastName" : "wang" }, "balance" : 500, "currency" : [ "CNY", "USD" ], "array" : [ "one", "two" ] }
    
    
    //会把一条记录拆分成两条
    db.account.aggregate([{$unwind:{path: "$currency"}}])
    
    { "_id" : ObjectId("5e204079b79fceaf9ea4be8f"), "name" : { "firstName" : "alice", "lastName" : "wang" }, "balance" : 500, "currency" : "CNY", "array" : [ "one", "two" ] }
    { "_id" : ObjectId("5e204079b79fceaf9ea4be8f"), "name" : { "firstName" : "alice", "lastName" : "wang" }, "balance" : 500, "currency" : "USD", "array" : [ "one", "two" ] }
    
    
  • 展开数组时添加元素位置

    > db.account.aggregate([{$unwind:{path:"$currency", includeArrayIndex: "ccyIndex"}}])
    { "_id" : ObjectId("5e203605b79fceaf9ea4be89"), "name" : "小一", "contact" : [ "11702908819", "西安", "陕西省" ], "currency" : "RMB", "ccyIndex" : null }
    { "_id" : ObjectId("5e204079b79fceaf9ea4be8f"), "name" : { "firstName" : "alice", "lastName" : "wang" }, "balance" : 500, "currency" : "CNY", "array" : [ "one", "two" ], "ccyIndex" : NumberLong(0) }
    { "_id" : ObjectId("5e204079b79fceaf9ea4be8f"), "name" : { "firstName" : "alice", "lastName" : "wang" }, "balance" : 500, "currency" : "USD", "array" : [ "one", "two" ], "ccyIndex" : NumberLong(1) }
    { "_id" : ObjectId("5e204079b79fceaf9ea4be90"), "name" : { "firstName" : "bob", "lastName" : "yang" }, "balance" : 400, "currency" : "GBP", "ccyIndex" : null }
    
  • 展开数组时保留数组或不存在数组的文档

    db.account.find()
    { "_id" : ObjectId("5e2035cab79fceaf9ea4be88"), "name" : "小柯", "contact" : [ "11702908819" ] }
    { "_id" : ObjectId("5e203605b79fceaf9ea4be89"), "name" : "小一", "contact" : [ "11702908819", "西安", "陕西省" ], "currency" : "RMB" }
    { "_id" : ObjectId("5e203630b79fceaf9ea4be8a"), "name" : "小一", "contact" : [ [ "00000", "777777" ], "西安", "陕西省" ] }
    { "_id" : ObjectId("5e20366cb79fceaf9ea4be8b"), "name" : "小一", "contact" : [ [ "00000", "777777" ], "西安", "陕西省" ], "ke" : { "aa" : "bb", "cc" : "dd" } }
    { "_id" : ObjectId("5e203689b79fceaf9ea4be8c"), "name" : "小一", "contact" : [ [ "00000", "777777" ], "西安", "陕西省" ], "balance" : 500 }
    { "_id" : ObjectId("5e204079b79fceaf9ea4be8f"), "name" : { "firstName" : "alice", "lastName" : "wang" }, "balance" : 500, "currency" : [ "CNY", "USD" ], "array" : [ "one", "two" ] }
    { "_id" : ObjectId("5e204079b79fceaf9ea4be90"), "name" : { "firstName" : "bob", "lastName" : "yang" }, "balance" : 400, "currency" : "GBP" }
    { "_id" : ObjectId("5e2053faf47293d1b9146730"), "name" : { "firstName" : "charlie", "lastName" : "gordon" }, "balance" : 100 }
    { "_id" : ObjectId("5e2053faf47293d1b9146731"), "name" : { "firstName" : "david", "lastName" : "wu" }, "balance" : 200, "currency" : [ ] }
    { "_id" : ObjectId("5e2053faf47293d1b9146732"), "name" : { "firstName" : "eddie", "lastName" : "kim" }, "balance" : 20, "currency" : null }
    
    
    > db.account.aggregate([{$unwind:{path:"$currency"}}])
    { "_id" : ObjectId("5e203605b79fceaf9ea4be89"), "name" : "小一", "contact" : [ "11702908819", "西安", "陕西省" ], "currency" : "RMB" }
    { "_id" : ObjectId("5e204079b79fceaf9ea4be8f"), "name" : { "firstName" : "alice", "lastName" : "wang" }, "balance" : 500, "currency" : "CNY", "array" : [ "one", "two" ] }
    { "_id" : ObjectId("5e204079b79fceaf9ea4be8f"), "name" : { "firstName" : "alice", "lastName" : "wang" }, "balance" : 500, "currency" : "USD", "array" : [ "one", "two" ] }
    { "_id" : ObjectId("5e204079b79fceaf9ea4be90"), "name" : { "firstName" : "bob", "lastName" : "yang" }, "balance" : 400, "currency" : "GBP" }
    
  • 展开数组时保留空数组或不存在数组的文档

    > db.account.aggregate([{$unwind:{path:"$currency", preserveNullAndEmptyArrays: true}}])
    { "_id" : ObjectId("5e2035cab79fceaf9ea4be88"), "name" : "小柯", "contact" : [ "11702908819" ] }
    { "_id" : ObjectId("5e203605b79fceaf9ea4be89"), "name" : "小一", "contact" : [ "11702908819", "西安", "陕西省" ], "currency" : "RMB" }
    { "_id" : ObjectId("5e203630b79fceaf9ea4be8a"), "name" : "小一", "contact" : [ [ "00000", "777777" ], "西安", "陕西省" ] }
    { "_id" : ObjectId("5e20366cb79fceaf9ea4be8b"), "name" : "小一", "contact" : [ [ "00000", "777777" ], "西安", "陕西省" ], "ke" : { "aa" : "bb", "cc" : "dd" } }
    { "_id" : ObjectId("5e203689b79fceaf9ea4be8c"), "name" : "小一", "contact" : [ [ "00000", "777777" ], "西安", "陕西省" ], "balance" : 500 }
    { "_id" : ObjectId("5e204079b79fceaf9ea4be8f"), "name" : { "firstName" : "alice", "lastName" : "wang" }, "balance" : 500, "currency" : "CNY", "array" : [ "one", "two" ] }
    { "_id" : ObjectId("5e204079b79fceaf9ea4be8f"), "name" : { "firstName" : "alice", "lastName" : "wang" }, "balance" : 500, "currency" : "USD", "array" : [ "one", "two" ] }
    { "_id" : ObjectId("5e204079b79fceaf9ea4be90"), "name" : { "firstName" : "bob", "lastName" : "yang" }, "balance" : 400, "currency" : "GBP" }
    { "_id" : ObjectId("5e2053faf47293d1b9146730"), "name" : { "firstName" : "charlie", "lastName" : "gordon" }, "balance" : 100 }
    { "_id" : ObjectId("5e2053faf47293d1b9146731"), "name" : { "firstName" : "david", "lastName" : "wu" }, "balance" : 200 }
    { "_id" : ObjectId("5e2053faf47293d1b9146732"), "name" : { "firstName" : "eddie", "lastName" : "kim" }, "balance" : 20, "currency" : null }
    
  • 对银行账户文档进行排序

    > db.account.aggregate([{$sort:{balance:1, "name.lastName": -1}}])
    { "_id" : ObjectId("5e2035cab79fceaf9ea4be88"), "name" : "小柯", "contact" : [ "11702908819" ] }
    { "_id" : ObjectId("5e203605b79fceaf9ea4be89"), "name" : "小一", "contact" : [ "11702908819", "西安", "陕西省" ], "currency" : "RMB" }
    { "_id" : ObjectId("5e203630b79fceaf9ea4be8a"), "name" : "小一", "contact" : [ [ "00000", "777777" ], "西安", "陕西省" ] }
    { "_id" : ObjectId("5e20366cb79fceaf9ea4be8b"), "name" : "小一", "contact" : [ [ "00000", "777777" ], "西安", "陕西省" ], "ke" : { "aa" : "bb", "cc" : "dd" } }
    { "_id" : ObjectId("5e2053faf47293d1b9146732"), "name" : { "firstName" : "eddie", "lastName" : "kim" }, "balance" : 20, "currency" : null }
    { "_id" : ObjectId("5e2053faf47293d1b9146730"), "name" : { "firstName" : "charlie", "lastName" : "gordon" }, "balance" : 100 }
    { "_id" : ObjectId("5e2053faf47293d1b9146731"), "name" : { "firstName" : "david", "lastName" : "wu" }, "balance" : 200, "currency" : [ ] }
    { "_id" : ObjectId("5e204079b79fceaf9ea4be90"), "name" : { "firstName" : "bob", "lastName" : "yang" }, "balance" : 400, "currency" : "GBP" }
    { "_id" : ObjectId("5e204079b79fceaf9ea4be8f"), "name" : { "firstName" : "alice", "lastName" : "wang" }, "balance" : 500, "currency" : [ "CNY", "USD" ], "array" : [ "one", "two" ] }
    { "_id" : ObjectId("5e203689b79fceaf9ea4be8c"), "name" : "小一", "contact" : [ [ "00000", "777777" ], "西安", "陕西省" ], "balance" : 500 }
    
发布了158 篇原创文章 · 获赞 26 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/qq_41650354/article/details/103811612