zoukankan      html  css  js  c++  java
  • MongoDB学习笔记(一)-Insert操作

    MongoDB插入

    Insert Documents

    • menu
      • insert Behavior
      • insert Methods

    插入行为

    * 如果集合不存在,插入操作将创建集合。
    * 在集合中,具有唯一主键`_id`。如果在插入文件中未声明`_id`;MongoDB将自动使用`ObjectIds`作为`_id`

    插入数据的方法

    MongoDB提供了保存数据的方法一共有三个:
    
        1. db.collection.insertOne()
        2. db.collection.insertMany()
        3. db.collection.insert()

    db.collection.insertOne()

    
    
    *3.2版本*
    将单个文档插入到一个集合,
     
    db.users.insertOne(
       {
          name: "sue",
          age: 19,
          status: "P"
       }
    )
    //会返回文档的操作状态。
    {
       "acknowledged" : true,
       "insertedId" : ObjectId("5742045ecacf0ba0c3fa82b0")
    }

    db.collection.insertMany()

    *3.2版本*
    将文档数组插入到一个集合,
    db.users.insertMany(
       [
         { name: "bob", age: 42, status: "A", },
         { name: "ahn", age: 22, status: "A", },
         { name: "xi", age: 34, status: "D", }
       ]
    )
    //会返回文档的操作状态。
    {
       "acknowledged" : true,
       "insertedIds" : [
          ObjectId("57420d48cacf0ba0c3fa82b1"),
          ObjectId("57420d48cacf0ba0c3fa82b2"),
          ObjectId("57420d48cacf0ba0c3fa82b3")
       ]
    }

    db.collection.insert()

    将单个或多个文档到一个集合。要插入一个单一的文件,传递文档;插入多个文件,传递文档数组。
    eg:
    //插入单个对象
    db.users.insert(
       {
          name: "sue",
          age: 19,
          status: "P"
       }
    )
    //返回一个 WriteResult 对象;如果插入错误,会返回错误信息
    WriteResult({ "nInserted" : 1 })
    
    //插入数组
    db.users.insert(
       [
         { name: "bob", age: 42, status: "A", },
         { name: "ahn", age: 22, status: "A", },
         { name: "xi", age: 34, status: "D", }
       ]
    )
    //返回 BulkWriteResult 对象
    BulkWriteResult({
       "writeErrors" : [ ],
       "writeConcernErrors" : [ ],
       "nInserted" : 3,
       "nUpserted" : 0,
       "nMatched" : 0,
       "nModified" : 0,
       "nRemoved" : 0,
       "upserted" : [ ]
    })

    同样能实现插入效果的方法

    • db.collection.update() 当upsert为true时//第三个参数
    • db.collection.updateOne() 当upsert为true时//第三个参数
    • db.collection.updateMany() 当upsert为true时//第三个参数
    • db.collection.findAndModify() 当upsert为true时**
    • db.collection.findAndModify() 当upsert为true时**
    • db.collection.findOneAndReplace() 当upsert为true时
    • db.collection.save().
    • db.collection.bulkWrite().

    db.collection.save()

    db.collection.save(doc) 若doc含有_id且在集合中存在,这将会替换集合内的文档(update),不存在则是insert该文档,若不存在_id,则是insert

  • 相关阅读:
    【Vue】Re19 Promise
    【Vue】Re17 Router 第四部分(参数传递,守卫函数)
    【Vue】Re16 Router 第三部分(懒加载、子路由)
    【Vue】Re15 Router 第二部分(缺省路由、动态路由)
    【Vue】Re14 Router 第一部分(入门案例)
    【Vue】Re13 CLI(Command Line Interface)
    【Vue】Re12 Webpack 第三部分(插件、热部署、配置分离)
    【Vue】Re11 Vue 与 Webpack
    【Vue】Re10 Webpack 第二部分(Loader)
    11-26日测试
  • 原文地址:https://www.cnblogs.com/weiwei-python/p/14078911.html
Copyright © 2011-2022 走看看