zoukankan      html  css  js  c++  java
  • MongoDB save()方法和insert()方法的区别

    MongoDB save()方法和insert()方法的区别

    首先看官方文档怎么说的

    Updates an existing document or inserts a new document, depending on its document parameter

    save方法有更新和插入两种功能,到底是插入还是更新文档取决于save的参数。那么到底是依赖于哪个参数呢?继续看

    If the document does not contain an _id field, then the save() method calls the insert() method. During the operation, the mongo shell will create an ObjectId and assign it to the _id field.

    可以看到决定是插入一个文档还是更新,取决于_id参数。如果能根据_id找到一个已经存在的文档,那么就更新。如果没有传入_id参数或者找不到存在的文档,那么就插入一个新文档。

    举一个官方的例子

    不带_id参数

    db.products.save( { item: "book", qty: 40 } )

    结果

    { "_id" : ObjectId("50691737d386d8fadbd6b01d"), "item" : "book", "qty" : 40 }

    MongoDb客户端驱动会自动为你生成一个默认
    ObjectId作为_id。

    带_id参数,但是找不到一个已经存在的文档

    db.products.save( { _id: 100, item: "water", qty: 30 } )

    结果

    { "_id" : 100, "item" : "water", "qty" : 30 }

    还是插入一个新文档,但是_id不会自动生成。

    带_id参数,但是有存在的文档

    db.products.save( { _id : 100, item : "juice" } )

    结果

    { "_id" : 100, "item" : "juice" }

    更新了文档

    总结
    1. insert: 若新增数据的主键已经存在,则会抛 org.springframework.dao.DuplicateKeyException 异常提示主键重复,不保存当前数据。
    2. save: 若新增数据的主键已经存在,则会对当前已经存在的数据进行修改操作。
  • 相关阅读:
    spring boot中 使用http请求
    spring boot 多层级mapper
    spring boot 使用拦截器,注解 实现 权限过滤
    spring boot 集成mybatis报错
    spring boot 使用拦截器 实现 用户登录拦截
    mac eclipse 删除不用的workspace
    maven+eclipse+mac+tomcat 多模块发布
    启动spring boot 异常
    安装 redis [standlone模式]
    quartz项目中的运用
  • 原文地址:https://www.cnblogs.com/lanqi/p/8535390.html
Copyright © 2011-2022 走看看