MongoDB使用BSON文件存储在collection中,本文主要介绍MongoDB中的写操作和优化策略。

主要有三种写操作:
        Create
        Update
        Delete

Create:可以分为两种基本操作——insert和updates with the upsert option

Insert()

BSON文件最大为16M;_id通常作为主key
为了测试写操作是否成功,可以调用getLastError函数{ getLastError: 1 }

db.collection.insert( <document> )
insert方法在第一次调用的时候,自动创建collection。

以下例子中bios为collection名,根据自己情况修改。
例如:
db.bios.insert(
   {
     _id: 1,
     name: { first: 'John', last: 'Backus' },
     birth: new Date('Dec 03, 1924'),
     death: new Date('Mar 17, 2007'),
     contribs: [ 'Fortran', 'ALGOL', 'Backus-Naur Form', 'FP' ],
     awards: [
               {
                 award: 'W.W. McDowell Award',
                 year: 1967,
                 by: 'IEEE Computer Society'
               },
               {
                 award: 'National Medal of Science',
                 year: 1975,
                 by: 'National Science Foundation'
               },
               {
                 award: 'Turing Award',
                 year: 1977,
                 by: 'ACM'
               },
               {
                 award: 'Draper Prize',
                 year: 1993,
                 by: 'National Academy of Engineering'
               }
             ]
   }
)
如果插入操作没有指定_id,则会自动生成一个唯一的id。

使用中括号,同时插入多个文档。
db.bios.insert(
   [
     {
       _id: 3,
       name: { first: 'Grace', last: 'Hopper' },
       title: 'Rear Admiral',
       birth: new Date('Dec 09, 1906'),
       death: new Date('Jan 01, 1992'),
       contribs: [ 'UNIVAC', 'compiler', 'FLOW-MATIC', 'COBOL' ],
       awards: [
                 {
                   award: 'Computer Sciences Man of the Year',
                   year: 1969,
                   by: 'Data Processing Management Association'
                 },
                 {
                   award: 'Distinguished Fellow',
                   year: 1973,
                   by: ' British Computer Society'
                 },
                 {
                   award: 'W. W. McDowell Award',
                   year: 1976,
                   by: 'IEEE Computer Society'
                 },
                 {
                   award: 'National Medal of Technology',
                   year: 1991,
                   by: 'United States'
                 }
               ]
     },
     {
       _id: 4,
       name: { first: 'Kristen', last: 'Nygaard' },
       birth: new Date('Aug 27, 1926'),
       death: new Date('Aug 10, 2002'),
       contribs: [ 'OOP', 'Simula' ],
       awards: [
                 {
                   award: 'Rosing Prize',
                   year: 1999,
                   by: 'Norwegian Data Association'
                 },
                 {
                   award: 'Turing Award',
                   year: 2001,
                   by: 'ACM'
                 },
                 {
                   award: 'IEEE John von Neumann Medal',
                   year: 2001,
                   by: 'IEEE'
                 }
               ]
     },
     {
       _id: 5,
       name: { first: 'Ole-Johan', last: 'Dahl' },
       birth: new Date('Oct 12, 1931'),
       death: new Date('Jun 29, 2002'),
       contribs: [ 'OOP', 'Simula' ],
       awards: [
                 {
                   award: 'Rosing Prize',
                   year: 1999,
                   by: 'Norwegian Data Association'
                 },
                 {
                   award: 'Turing Award',
                   year: 2001,
                   by: 'ACM'
                 },
                 {
                   award: 'IEEE John von Neumann Medal',
                   year: 2001,
                   by: 'IEEE'
                 }
               ]
     }
   ]
)
调用save()函数,通过查询collection中的_id域,来决定使用insert还是update。

upsert flags 当插入的文档已经存在,需要对原文当进行覆盖的时候使用此标记。
db.collection.update( <query>,
                      <update>,
                      { upsert: true } )

如果没有文档符合查询要求<query>,则插入文档,举例如下:
db.bios.update(
   {
     _id: 7,
     name: { first: 'Ken', last: 'Thompson' }
   },
   {
     $set: {
             birth: new Date('Feb 04, 1943'),
             contribs: [ 'UNIX', 'C', 'B', 'UTF-8' ],
             awards: [
                       {
                         award: 'Turing Award',
                         year: 1983,
                         by: 'ACM'
                       },
                       {
                         award: 'IEEE Richard W. Hamming Medal',
                         year: 1990,
                         by: 'IEEE'
                       },
                       {
                         award: 'National Medal of Technology',
                         year: 1998,
                         by: 'United States'
                       },
                       {
                         award: 'Tsutomu Kanai Award',
                         year: 1999,
                         by: 'IEEE'
                       },
                       {
                         award: 'Japan Prize',
                         year: 2011,
                         by: 'The Japan Prize Foundation'
                       }
                     ]
           }
   },
   { upsert: true } //如果文档存在,覆盖
)

Update()
主要包括两种操作,update和save

db.collection.update( <query>, <update>, <options>
使用方法同insert中介绍。

下面分情况举例:
1、更新文件中的域
db.bios.update(
   { _id: 1 },
   {
     $set: { 'name.middle': 'Warner' },
   }
)
更新子文档name中的middle域为warner

2、添加新的域
db.bios.update(
   { _id: 3 },
   { $set: {
             mbranch: 'Navy',
             'name.aka': 'Amazing Grace'
           }
   }
)
添加mbranch域 和子文档name的aka域

3、移除域
db.bios.update(
   { _id: 3 },
   { $unset: { birth: 1 } }
)

4、更新数组
db.bios.update(
   { _id: 1 },
   { $set: { 'contribs.1': 'ALGOL 58' } }
)
更新contribs数组中第二个元素的值

5、定位,然后更新元素
db.bios.update(
       { _id: 3, 'contribs': 'compiler' },
       { $set: { 'contribs.$': 'A compiler' } }
    )
定位id为3,contribs中存在compiler元素的位置,更新为A compiler

6、向数组添加元素
db.bios.update(
   { _id: 1 },
   {
     $push: { awards: { award: 'IBM Fellow', year: 1963, by: 'IBM' } }
   }
)
添加一个新的awards域的元素

7、更新多个文档
db.bios.update(
   { 'awards.award': 'Turing' },
   { $set: { turing: true } },
   { multi: true }
)

save()函数可以用以下函数来解释:function save( doc ) {
  if( doc["_id"] ) {
       update( {_id: doc["_id"] }, doc, { upsert: true } );
    }
  else {
       insert(doc);
  }
}

Update Operators 操作符

Fields

Name Description
$inc Increments the value of the field by the specified amount.
$rename Renames a field.
$setOnInsert Sets the value of a field upon documentation creation during an upsert. Has no effect on update operations that modify existing documents.
$set Sets the value of a field in an existing document.
$unset Removes the specified field from an existing document.

Array Operators

Name Description
$ Acts as a placeholder to update the first element that matches the query condition in an update.
$addToSet Adds elements to an existing array only if they do not already exist in the set.
$pop Removes the first or last item of an array.
$pullAll Removes multiple values from an array.
$pull Removes items from an array that match a query statement.
$pushAll Deprecated. Adds several items to an array.
$push Adds an item to an array.

Modifiers

Name Description
$each Modifies the $push and $addToSet operators to append multiple items for array updates.
$slice Modifies the $push operator to limit the size of updated arrays.
$sort Modifies the $push operator to reorder documents stored in an array.

Bitwise

Name Description
$bit Performs bitwise AND and OR updates of integer values.

Isolation

  Name Description
$isolated Modifies behavior of multi-updates to improve the isolation of the operation.

MongoDB—— 写操作 Core MongoDB Operations (CRUD)的更多相关文章

  1. MongoDB—— 读操作 Core MongoDB Operations (CRUD)

    本文主要介绍内容:从MongoDB中请求数据的不同的方法 Note:All of the examples in this document use the mongo shell interface ...

  2. .Net Core MongoDB 简单操作。

    一:MongoDB 简单操作类.这里引用了MongoDB.Driver. using MongoDB.Bson; using MongoDB.Driver; using System; using S ...

  3. MongoDB via Dotnet Core数据映射详解

    用好数据映射,MongoDB via Dotnet Core开发变会成一件超级快乐的事.   一.前言 MongoDB这几年已经成为NoSQL的头部数据库. 由于MongoDB free schema ...

  4. MongoDB常用操作一查询find方法db.collection_name.find()

    来:http://blog.csdn.net/wangli61289/article/details/40623097 https://docs.mongodb.org/manual/referenc ...

  5. [置顶] MongoDB 分布式操作——分片操作

    MongoDB 分布式操作——分片操作 描述: 像其它分布式数据库一样,MongoDB同样支持分布式操作,且MongoDB将分布式已经集成到数据库中,其分布式体系如下图所示: 所谓的片,其实就是一个单 ...

  6. [转]MongoDB更新操作replaceOne()实例讲解

    最近正在学习MongoDB,作为数据库的学习当然是要从CRUD开始学起了.这篇文章默认读者是知道如何安装MongoDB.如何运行MongoDB实例以及了解了MongoDB中的collection.do ...

  7. MongoDB常用操作一查询find方法(转)

    来:http://blog.csdn.net/wangli61289/article/details/40623097 https://docs.mongodb.org/manual/referenc ...

  8. MongoDB常用操作整理

    Mongodb:是一种NoSQL数据库,NoSQL:Not Only SQLSQL: 数据表->JDBC读取->POJO(VO.PO)->控制层转化为JSON数据->客户端 这 ...

  9. 笔记-mongodb数据操作

    笔记-mongodb数据操作 1.      数据操作 1.1.    插入 db.COLLECTION_NAME.insert(document) 案例: db.inventory.insertOn ...

随机推荐

  1. hdu 2007 - 平方和与立方和

    题目大意: 给定一段连续的整数,求出他们中所有偶数的平方和以及所有奇数的立方和. 解答: 坑你没商量!要考虑输入数a,b的大小.如果a>b,需要交换a,b的值. 1: #include<s ...

  2. DNS(企业级)

    构建DNS(企业级) 1.硬件选型 CPU:12C以上配置 内存:16G 网络:千兆 2.初始化系统配置 关闭 iptables service iptables stop chkconfig ipt ...

  3. 【原】js检测移动端横竖屏

    摘要:上周做了一个小项目,但是要放到我们的app上,然而需要横竖屏使用不同的样式.横屏一套,竖屏一套.调用了手机APP那里的api,可是他们那里ios和安卓返回的不一样. 各种头疼.于是用了css3的 ...

  4. js024-最佳实践

    js024-最佳实践 本章内容: 可维护的代码 保证代码性能 部署代码 24.1 可维护性 24.1.1 代码的可维护性 代码可维护性的特征: 特性 说明 可理解性 其他人可以理解它的用途和一般途径 ...

  5. 转:netflix推荐系统竞赛

    原文链接:Netflix recommendations: beyond the 5 stars (Part 1), (Part 2) 原文作者:Xavier Amatriain and Justin ...

  6. C# “配置系统未能初始化” 异常解决

    使用App.config配置参数,读取参数出现错误 “System.Configuration.ConfigurationErrorsException”类型的未经处理的异常在 System.Conf ...

  7. Nancy总结(二)记一次Nancy 框架中遇到的坑

    记一次Nancy 框架中遇到的坑 前几天,公司一个项目运行很久的Nancy框架的网站,遇到了一个很诡异的问题.Session 对象跳转到另外一个页面的时候,session对象被清空了,导致用户登录不上 ...

  8. composer错误收集

    1. Problem 1 - The requested package ** is satisfiable by ** but these conflict with your requiremen ...

  9. 经纬度距离计算Java实现代码

    public class test { private static double rad(double d) { return d * Math.PI / 180.0; } public stati ...

  10. 用apache-cxf生成webservice客户端的时候报错Parameter: shead already exists for method

    版本apache-cxf-3.1.0 命令如下:wsdl2java -p com.wz.interfaces -d ./src -client ./ws/xxx.wsdl 报错如下: WSDLToJa ...