MongoDB——基础篇(文档操作)

新增

单个插入

  • insert:若插入的数据主键已经存在,则会抛DuplicateKeyException异常,提示主键重复,不保存当前数据

    > db.createCollection("emps")
    { "ok" : 1 }
    > db.emps.insert({x:1})
    WriteResult({ "nInserted" : 1 })
    
  • save:如果 _id 主键存在则更新数据,如果不存在就插入数据

    > db.emps.save({x:2})
    WriteResult({ "nInserted" : 1 })
    
  • insertOne:支持writeConcern

    > db.emps.insertOne({x:3})
    {
            "acknowledged" : true,
            "insertedId" : ObjectId("628e468160e30920704dfeb0")
    }
    
    > db.emps.insertOne({x:4},{writeConcern:0})
    {
            "acknowledged" : true,
            "insertedId" : ObjectId("628e47da60e30920704dfeb2")
    }
    

    writeConcern决定一个写操作落到多少个节点上才算成功。

    writeConcern的取值包括:

    0:发起写操作,不关心是否成功;
    1~集群最大数据节点数:写操作需要被复制到指定节点数才算成功;
    majority:写操作需要被复制到大多数节点上才算成功;。

批量插入

  • insert

    > db.emps.insert([{x:5},{x:6}])
    BulkWriteResult({
            "writeErrors" : [ ],
            "writeConcernErrors" : [ ],
            "nInserted" : 2,
            "nUpserted" : 0,
            "nMatched" : 0,
            "nModified" : 0,
            "nRemoved" : 0,
            "upserted" : [ ]
    })
    
  • save

    > db.emps.save([{x:7},{x:8},{x:9}])
    BulkWriteResult({
            "writeErrors" : [ ],
            "writeConcernErrors" : [ ],
            "nInserted" : 3,
            "nUpserted" : 0,
            "nMatched" : 0,
            "nModified" : 0,
            "nRemoved" : 0,
            "upserted" : [ ]
    })
    
  • insertMany

    > db.emps.insertMany([{x:10},{x:11}])
    {
            "acknowledged" : true,
            "insertedIds" : [
                    ObjectId("628e4962495e82d49b890573"),
                    ObjectId("628e4962495e82d49b890574")
            ]
    }
    
    > db.emps.insertMany([{x:12},{x:13}],{writeConcern:0})
    {
            "acknowledged" : true,
            "insertedIds" : [
                    ObjectId("628e497d495e82d49b890575"),
                    ObjectId("628e497d495e82d49b890576")
            ]
    }
    
  • load(“xxx.js”)

    var tags = ["nosql","mongodb","document","developer","popular"];
    var types = ["technology","sociality","travel","novel","literature"];
    var books=[];
    for(var i=0;i<50;i++){
    var typeIdx = Math.floor(Math.random()*types.length);
    var tagIdx = Math.floor(Math.random()*tags.length);
    var favCount = Math.floor(Math.random()*100);
    var book = {
    title: "book-"+i,
    type: types[typeIdx],
    tag: tags[tagIdx],
    favCount: favCount,
    author: "xxx"+i
    };
    books.push(book)
    }
    db.books.insertMany(books);
    
    [root@VM-24-2-centos js]# vim book.js
    [root@VM-24-2-centos js]# mongo --port=27017
    MongoDB shell version v4.4.6
    connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
    Implicit session: session { "id" : UUID("ecd09547-db6d-4d9e-a4d9-5a928a01127c") }
    MongoDB server version: 4.4.6
    > use appdb
    switched to db appdb
    > db.auth("app","app")
    1
    > db.createCollection("books")
    { "ok" : 1 }
    > load("book.js")
    true
    

查询

db.collection.find(query, projection)
  • query

    可选,使用查询操作符指定查询条件;

  • projection

    可选,使用投影操作符指定返回的键。查询时返回文档中所有键值, 只需省略该参 数即可(默认省略)。投影时,id为1的时候,其他字段必须是1;id是0的时候,其他字段可以是 0;如果没有_id字段约束,多个其他字段必须同为0或同为1;

无条件查询

如果查询返回的条目数量较多,mongo shell则会自动实现分批显示默认情况下每次只显示20条,可以输入it命令读取下一批。

测试
> db.books.find()
{ "_id" : ObjectId("628e4b78a8cff71722ae2779"), "title" : "book-0", "type" : "technology", "tag" : "popular", "favCount" : 64, "author" : "xxx0" }
{ "_id" : ObjectId("628e4b78a8cff71722ae277a"), "title" : "book-1", "type" : "sociality", "tag" : "document", "favCount" : 46, "author" : "xxx1" }
{ "_id" : ObjectId("628e4b78a8cff71722ae277b"), "title" : "book-2", "type" : "travel", "tag" : "document", "favCount" : 23, "author" : "xxx2" }
{ "_id" : ObjectId("628e4b78a8cff71722ae277c"), "title" : "book-3", "type" : "literature", "tag" : "developer", "favCount" : 33, "author" : "xxx3" }
{ "_id" : ObjectId("628e4b78a8cff71722ae277d"), "title" : "book-4", "type" : "travel", "tag" : "popular", "favCount" : 16, "author" : "xxx4" }
{ "_id" : ObjectId("628e4b78a8cff71722ae277e"), "title" : "book-5", "type" : "sociality", "tag" : "popular", "favCount" : 42, "author" : "xxx5" }
{ "_id" : ObjectId("628e4b78a8cff71722ae277f"), "title" : "book-6", "type" : "sociality", "tag" : "popular", "favCount" : 22, "author" : "xxx6" }
{ "_id" : ObjectId("628e4b78a8cff71722ae2780"), "title" : "book-7", "type" : "literature", "tag" : "popular", "favCount" : 34, "author" : "xxx7" }
{ "_id" : ObjectId("628e4b78a8cff71722ae2781"), "title" : "book-8", "type" : "literature", "tag" : "mongodb", "favCount" : 25, "author" : "xxx8" }
{ "_id" : ObjectId("628e4b78a8cff71722ae2782"), "title" : "book-9", "type" : "novel", "tag" : "document", "favCount" : 59, "author" : "xxx9" }
{ "_id" : ObjectId("628e4b78a8cff71722ae2783"), "title" : "book-10", "type" : "sociality", "tag" : "popular", "favCount" : 53, "author" : "xxx10" }
{ "_id" : ObjectId("628e4b78a8cff71722ae2784"), "title" : "book-11", "type" : "sociality", "tag" : "developer", "favCount" : 59, "author" : "xxx11" }
{ "_id" : ObjectId("628e4b78a8cff71722ae2785"), "title" : "book-12", "type" : "novel", "tag" : "developer", "favCount" : 67, "author" : "xxx12" }
{ "_id" : ObjectId("628e4b78a8cff71722ae2786"), "title" : "book-13", "type" : "travel", "tag" : "document", "favCount" : 31, "author" : "xxx13" }
{ "_id" : ObjectId("628e4b78a8cff71722ae2787"), "title" : "book-14", "type" : "literature", "tag" : "nosql", "favCount" : 49, "author" : "xxx14" }
{ "_id" : ObjectId("628e4b78a8cff71722ae2788"), "title" : "book-15", "type" : "novel", "tag" : "mongodb", "favCount" : 66, "author" : "xxx15" }
{ "_id" : ObjectId("628e4b78a8cff71722ae2789"), "title" : "book-16", "type" : "sociality", "tag" : "popular", "favCount" : 83, "author" : "xxx16" }
{ "_id" : ObjectId("628e4b78a8cff71722ae278a"), "title" : "book-17", "type" : "literature", "tag" : "nosql", "favCount" : 54, "author" : "xxx17" }
{ "_id" : ObjectId("628e4b78a8cff71722ae278b"), "title" : "book-18", "type" : "novel", "tag" : "nosql", "favCount" : 58, "author" : "xxx18" }
{ "_id" : ObjectId("628e4b78a8cff71722ae278c"), "title" : "book-19", "type" : "literature", "tag" : "developer", "favCount" : 68, "author" : "xxx19" }
Type "it" for more
> it
{ "_id" : ObjectId("628e4b78a8cff71722ae27a1"), "title" : "book-40", "type" : "technology", "tag" : "nosql", "favCount" : 9, "author" : "xxx40" }
{ "_id" : ObjectId("628e4b78a8cff71722ae27a2"), "title" : "book-41", "type" : "novel", "tag" : "document", "favCount" : 62, "author" : "xxx41" }
{ "_id" : ObjectId("628e4b78a8cff71722ae27a3"), "title" : "book-42", "type" : "sociality", "tag" : "popular", "favCount" : 21, "author" : "xxx42" }
{ "_id" : ObjectId("628e4b78a8cff71722ae27a4"), "title" : "book-43", "type" : "travel", "tag" : "developer", "favCount" : 83, "author" : "xxx43" }
{ "_id" : ObjectId("628e4b78a8cff71722ae27a5"), "title" : "book-44", "type" : "travel", "tag" : "mongodb", "favCount" : 10, "author" : "xxx44" }
{ "_id" : ObjectId("628e4b78a8cff71722ae27a6"), "title" : "book-45", "type" : "novel", "tag" : "mongodb", "favCount" : 66, "author" : "xxx45" }
{ "_id" : ObjectId("628e4b78a8cff71722ae27a7"), "title" : "book-46", "type" : "travel", "tag" : "nosql", "favCount" : 84, "author" : "xxx46" }
{ "_id" : ObjectId("628e4b78a8cff71722ae27a8"), "title" : "book-47", "type" : "travel", "tag" : "mongodb", "favCount" : 89, "author" : "xxx47" }
{ "_id" : ObjectId("628e4b78a8cff71722ae27a9"), "title" : "book-48", "type" : "novel", "tag" : "popular", "favCount" : 61, "author" : "xxx48" }
{ "_id" : ObjectId("628e4b78a8cff71722ae27aa"), "title" : "book-49", "type" : "sociality", "tag" : "developer", "favCount" : 77, "author" : "xxx49" }
> it
no cursor

条件查询

条件对照表
SQLMQL
a=1{a:1}
a<>1{a:{$ne:1}}
a>1{a:{$gt:1}}
a>=1{a:{$gte:1}}
a<1{a:{$lt:1}}
a<=1{a:{$lte:1}}
逻辑对照表
SQLMQL
a=1 and b=1{a:1,b:1}或{$and:[{a:1},{b:1}]}
a=1 or b=1{$or:[{a:1},{b:1}]}
a is null{a:{$exists:false}}
a in (1,2){a:{$in:[{1,2}]}}
a not in (1,2){a:{$nin:[{1,2}]}
测试
查询标签为mongodb且收藏数大于等于50的book
> db.books.find({$and:[{tag:"mongodb"},{favCount:{$gte:50}}]})
{ "_id" : ObjectId("628e4b78a8cff71722ae2788"), "title" : "book-15", "type" : "novel", "tag" : "mongodb", "favCount" : 66, "author" : "xxx15" }
{ "_id" : ObjectId("628e4b78a8cff71722ae2797"), "title" : "book-30", "type" : "novel", "tag" : "mongodb", "favCount" : 78, "author" : "xxx30" }
{ "_id" : ObjectId("628e4b78a8cff71722ae27a6"), "title" : "book-45", "type" : "novel", "tag" : "mongodb", "favCount" : 66, "author" : "xxx45" }
{ "_id" : ObjectId("628e4b78a8cff71722ae27a8"), "title" : "book-47", "type" : "travel", "tag" : "mongodb", "favCount" : 89, "author" : "xxx47" }
正则表达式查询
//使用正则表达式查找tag包含no字符串的book
> db.books.find({tag:{$regex:"no"}})
{ "_id" : ObjectId("628e4b78a8cff71722ae2787"), "title" : "book-14", "type" : "literature", "tag" : "nosql", "favCount" : 49, "author" : "xxx14" }
{ "_id" : ObjectId("628e4b78a8cff71722ae278a"), "title" : "book-17", "type" : "literature", "tag" : "nosql", "favCount" : 54, "author" : "xxx17" }
{ "_id" : ObjectId("628e4b78a8cff71722ae278b"), "title" : "book-18", "type" : "novel", "tag" : "nosql", "favCount" : 58, "author" : "xxx18" }
{ "_id" : ObjectId("628e4b78a8cff71722ae2791"), "title" : "book-24", "type" : "travel", "tag" : "nosql", "favCount" : 36, "author" : "xxx24" }
{ "_id" : ObjectId("628e4b78a8cff71722ae2792"), "title" : "book-25", "type" : "travel", "tag" : "nosql", "favCount" : 80, "author" : "xxx25" }
{ "_id" : ObjectId("628e4b78a8cff71722ae2794"), "title" : "book-27", "type" : "travel", "tag" : "nosql", "favCount" : 30, "author" : "xxx27" }
{ "_id" : ObjectId("628e4b78a8cff71722ae2796"), "title" : "book-29", "type" : "travel", "tag" : "nosql", "favCount" : 20, "author" : "xxx29" }
{ "_id" : ObjectId("628e4b78a8cff71722ae2798"), "title" : "book-31", "type" : "sociality", "tag" : "nosql", "favCount" : 50, "author" : "xxx31" }
{ "_id" : ObjectId("628e4b78a8cff71722ae2799"), "title" : "book-32", "type" : "travel", "tag" : "nosql", "favCount" : 26, "author" : "xxx32" }
{ "_id" : ObjectId("628e4b78a8cff71722ae27a0"), "title" : "book-39", "type" : "novel", "tag" : "nosql", "favCount" : 90, "author" : "xxx39" }
{ "_id" : ObjectId("628e4b78a8cff71722ae27a1"), "title" : "book-40", "type" : "technology", "tag" : "nosql", "favCount" : 9, "author" : "xxx40" }
{ "_id" : ObjectId("628e4b78a8cff71722ae27a7"), "title" : "book-46", "type" : "travel", "tag" : "nosql", "favCount" : 84, "author" : "xxx46" }
> 
排序
#指定按收藏数(favCount)升序返回
> db.books.find({tag:"nosql"}).sort({favCount:1})
{ "_id" : ObjectId("628e4b78a8cff71722ae27a1"), "title" : "book-40", "type" : "technology", "tag" : "nosql", "favCount" : 9, "author" : "xxx40" }
{ "_id" : ObjectId("628e4b78a8cff71722ae2796"), "title" : "book-29", "type" : "travel", "tag" : "nosql", "favCount" : 20, "author" : "xxx29" }
{ "_id" : ObjectId("628e4b78a8cff71722ae2799"), "title" : "book-32", "type" : "travel", "tag" : "nosql", "favCount" : 26, "author" : "xxx32" }
{ "_id" : ObjectId("628e4b78a8cff71722ae2794"), "title" : "book-27", "type" : "travel", "tag" : "nosql", "favCount" : 30, "author" : "xxx27" }
{ "_id" : ObjectId("628e4b78a8cff71722ae2791"), "title" : "book-24", "type" : "travel", "tag" : "nosql", "favCount" : 36, "author" : "xxx24" }
{ "_id" : ObjectId("628e4b78a8cff71722ae2787"), "title" : "book-14", "type" : "literature", "tag" : "nosql", "favCount" : 49, "author" : "xxx14" }
{ "_id" : ObjectId("628e4b78a8cff71722ae2798"), "title" : "book-31", "type" : "sociality", "tag" : "nosql", "favCount" : 50, "author" : "xxx31" }
{ "_id" : ObjectId("628e4b78a8cff71722ae278a"), "title" : "book-17", "type" : "literature", "tag" : "nosql", "favCount" : 54, "author" : "xxx17" }
{ "_id" : ObjectId("628e4b78a8cff71722ae278b"), "title" : "book-18", "type" : "novel", "tag" : "nosql", "favCount" : 58, "author" : "xxx18" }
{ "_id" : ObjectId("628e4b78a8cff71722ae2792"), "title" : "book-25", "type" : "travel", "tag" : "nosql", "favCount" : 80, "author" : "xxx25" }
{ "_id" : ObjectId("628e4b78a8cff71722ae27a7"), "title" : "book-46", "type" : "travel", "tag" : "nosql", "favCount" : 84, "author" : "xxx46" }
{ "_id" : ObjectId("628e4b78a8cff71722ae27a0"), "title" : "book-39", "type" : "novel", "tag" : "nosql", "favCount" : 90, "author" : "xxx39" }
> 
分页
> db.books.find().skip(8).limit(4)
{ "_id" : ObjectId("628e4b78a8cff71722ae2781"), "title" : "book-8", "type" : "literature", "tag" : "mongodb", "favCount" : 25, "author" : "xxx8" }
{ "_id" : ObjectId("628e4b78a8cff71722ae2782"), "title" : "book-9", "type" : "novel", "tag" : "document", "favCount" : 59, "author" : "xxx9" }
{ "_id" : ObjectId("628e4b78a8cff71722ae2783"), "title" : "book-10", "type" : "sociality", "tag" : "popular", "favCount" : 53, "author" : "xxx10" }
{ "_id" : ObjectId("628e4b78a8cff71722ae2784"), "title" : "book-11", "type" : "sociality", "tag" : "developer", "favCount" : 59, "author" : "xxx11" }
> 

更新

db.collection.update(query,update,options)
  • query:描述更新的查询条件
  • update:描述更新的动作及新的内容
  • options:描述更新的选项
  • upsert: 可选,如果不存在update的记录,是否插入新的记录。默认false,不插入
  • multi: 可选,是否按条件查询出的多条记录全部更新。 默认false,只更新找到的第一条记录
  • writeConcern :可选,决定一个写操作落到多少个节点上才算成功

操作符

操作符格式描述
$set{$set:{field:value}}指定一个键并更新值,若键不存在则创建
$unset{$unset : {field:1}}删除一个键
$inc{$inc : {field:value}}对数值类型进行增减
$rename{$rename : {old_field_name : new_field_name}}修改字段名称
$push{$push : {field : value}}将数值追加到数组中,若数组不存在则 会进行初始化
$pushAll{$pushAll : {field : value_array }}追加多个值到一个数组字段内
$pull{$pull : {field : _value}}从数组中删除指定的元素
$addToSet{$addToSet : {field : value } }添加元素到数组中,具有排重功能
$pop{$pop : {field : 1 }}删除数组的第一个或最后一个元素
更新单个文档
> db.books.update({tag:"nosql"},{$inc:{favCount:16}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
更新多个文档
  • updateOne:更新单个文档
  • updateMany:更新多个文档
  • multi选项
  • replaceOne:替换单个文档
> db.books.update({tag:"nosql"},{$inc:{favCount:16}},{"multi":true})
WriteResult({ "nMatched" : 12, "nUpserted" : 0, "nModified" : 12 })
upsert
> db.books.update(
... {title:"my book"},
... {$set:{tags:["nosql","mongodb"],type:"none",author:"fox"}},
... {upsert:true}
... )
WriteResult({
        "nMatched" : 0,
        "nUpserted" : 1,
        "nModified" : 0,
        "_id" : ObjectId("628e5dde28c7689469c84ff9")
})
> 
replace
> db.books.update(
... {title:"my book"},
... {justTitle:"my first book"}
... )
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> 
findAndModify

该操作会返回符合查询条件的文档数据,并完成对文档的修改,但只能更新单个文档

//将某个book文档的收藏数(favCount)加1
db.books.findAndModify({
query:{_id:ObjectId("61caa09ee0782536660494dd")},
update:{$inc:{favCount:1}}
})

删除

  • remove

    • 需要配合查询条件使用,符合查询条件的文档会被删除

    • 指定一个空文档条件会删除所有文档

    • db.user.remove({age:28})// 删除age 等于28的记录
      db.user.remove({age:{$lt:25}}) // 删除age 小于25的记录
      db.user.remove( { } ) // 删除所有记录
      db.user.remove() //报错
      
  • deleteOne

    • db.books.deleteOne ({ type:"novel" }) //删除 type等于novel 的一个文档
      
  • deleteMany

    • db.books.deleteMany ({ type:"novel" }) //删除 type等于 novel 的全部文档
      
    • db.books.deleteMany ({}) //删除集合下全部文档
      
  • 返回被删除文档

    • findOneAndDelete

    • > db.books.findOneAndDelete({type:"novel"})
      {
              "_id" : ObjectId("628e4b78a8cff71722ae2782"),
              "title" : "book-9",
              "type" : "novel",
              "tag" : "document",
              "favCount" : 59,
              "author" : "xxx9"
      }
      > 
      
    • findOneAndDelete命令还允许定义“删除的顺序”,即按照指定顺序删除找到的第一个文档;

      利用这个特性,findOneAndDelete可以实现队列的先进先出;

      db.books.findOneAndDelete({type:"novel"},{sort:{favCount:1}})
      

“628e4b78a8cff71722ae2782”),
“title” : “book-9”,
“type” : “novel”,
“tag” : “document”,
“favCount” : 59,
“author” : “xxx9”
}
>
```

  • findOneAndDelete命令还允许定义“删除的顺序”,即按照指定顺序删除找到的第一个文档;

    利用这个特性,findOneAndDelete可以实现队列的先进先出;

    db.books.findOneAndDelete({type:"novel"},{sort:{favCount:1}})
    
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SONNIE在路上

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值