实言 發表於 2020-6-5 10:31:00

MongoDB 4.X CRUD基本操作

<p>本文总结了MongoDB 4.X在mongo shell客户端涉及的对文档一些基本的增删改查操作,即CRUD操作。主要结合了自己平时使用MongoDB的操作命令,更详细的命令可以参考官方文档: <strong>https://docs.mongodb.com/manual/crud/</strong> 。</p>
<h2 id="创建create-operations">创建(Create Operations)</h2>
<p>创建(Create Operations)也叫插入操作,当集合不存在时,插入操作同时也会创建集合。MongoDB提供以下几种插入文档方法:</p>
<ul>
<li><strong>db.collection.insert()</strong>:在指定集合中插入单个或多个文档。</li>
<li><strong>db.collection.insertOne()</strong>:在指定集合中插入单个文档(版本3.2新增)。</li>
<li><strong>db.collection.insertMany()</strong>:在指定集合中插入多个文档(版本3.2新增)。</li>
</ul>
<h3 id="dbcollectioninsert">db.collection.insert()</h3>
<p>在平时的使用当中,<strong>db.collection.insert()</strong>是我用得最多的文档插入方式,具体的语法格式如下:</p>
<pre><code class="language-javascript">db.collection.insert(
   &lt;document or array of documents&gt;,
   {
   writeConcern: &lt;document&gt;,
   ordered: &lt;boolean&gt;
   }
)
</code></pre>
<p>参数说明:</p>
<ul>
<li><strong>document</strong>:指定一个或多个文档;</li>
<li><strong>writeConcern</strong>:文档写入确认级别(可选),关于读写策略确认级别,以后再进行讨论;</li>
<li><strong>ordered</strong>:指定文档是否按顺序插入(可选),默认为true;
<ul>
<li>当指定为true时,插入多个文档时将文档排序保存在一个数组中进行插入,如果其中有一个文档插入失败,则会导致数组中余下的文档不进行插入操作;</li>
<li>当指定为false时,插入多个文档时将文档不进行排序保存在一个数组中进行插入,如果其中有一个文档插入失败,则不影响数组中余下的文档进行插入操作。</li>
</ul>
</li>
</ul>
<p>如果插入的文档当中没有指定<code>_id</code>字段,则MongoDB会自动为文档生成具有唯一<code>ObjectId</code>值的字段<code>_id</code>。</p>
<p>使用示例:</p>
<pre><code class="language-javascript">// 没有指定_id字段的插入单个文档
db.products.insert( { item: "card", qty: 15 } );

// 指定_id字段的插入单个文档
db.products.insert( { _id: 10, item: "box", qty: 20 } );

// 插入多个文档,不进行排序,多个文档包含在数组[]中
db.products.insert(
   [
   { _id: 11, item: "pencil", qty: 50, type: "no.2" },
   { item: "pen", qty: 20 },
   { item: "eraser", qty: 25 }
   ]
);

// 插入多个文档,并进行排序
db.products.insert(
   [
   { _id: 20, item: "lamp", qty: 50, type: "desk" },
   { _id: 21, item: "lamp", qty: 20, type: "floor" },
   { _id: 22, item: "bulk", qty: 100 }
   ],
   { ordered: false }
);

</code></pre>
<h3 id="dbcollectioninsertone">db.collection.insertOne()</h3>
<p>语法格式如下:</p>
<pre><code class="language-javascript">db.collection.insertOne(
   &lt;document&gt;,
   {
      writeConcern: &lt;document&gt;
   }
)
</code></pre>
<p>参数说明:</p>
<p>参考<strong>db.collection.insert()</strong>的参数说明。</p>
<p>使用示例:</p>
<pre><code class="language-javascript">// 单行插入文档,关于_id字段指定与否也与db.collection.insert()一致
db.products.insertOne( { item: "card", qty: 15 } );
</code></pre>
<h3 id="dbcollectioninsertmany">db.collection.insertMany()</h3>
<p>语法格式如下:</p>
<pre><code class="language-js">db.collection.insertMany(
   [ &lt;document 1&gt; , &lt;document 2&gt;, ... ],
   {
      writeConcern: &lt;document&gt;,
      ordered: &lt;boolean&gt;
   }
)
</code></pre>
<p>参数说明:</p>
<p>参考<strong>db.collection.insert()</strong>的参数说明。</p>
<p>使用示例:</p>
<p>参考<strong>db.collection.insert()</strong>的参数说明。</p>
<h3 id="关于返回确认信息">关于返回确认信息</h3>
<p><strong>db.collection.insert()</strong>在插入文档成功之后返回的信息相对较为简洁:</p>
<pre><code class="language-javascript">db.products.insert( { item: "card", qty: 15 } );
WriteResult({ "nInserted" : 1, "writeConcernError" : [ ] })
</code></pre>
<p><strong>db.collection.insertOne()</strong>和<strong>db.collection.insertMany()</strong>返回的信息较为详细:</p>
<pre><code class="language-javascript">db.products.insertOne( { item: "card", qty: 15 } );
{
    "acknowledged": true,
    "insertedId": ObjectId("5eccbd214139000074003be8")
}

db.products.insertMany( [
      { _id: 10, item: "large box", qty: 20 },
      { _id: 11, item: "small box", qty: 55 },
      { _id: 12, item: "medium box", qty: 30 }
   ] );
{
    "acknowledged": true,
    "insertedIds": [
      10,
      11,
      12
    ]
}
</code></pre>
<h2 id="查询read-operations">查询(Read Operations)</h2>
<p>查询(Read Operations)读操作,是对集合中已存在的文档进行查询,即对应关系型数据库当中的<code>select</code>操作,比如MySQL,MongoDB提供以下几种主要查询文档方法:</p>
<ul>
<li><strong>db.collection.find()</strong>:查询指定集合中满足条件的一个或多个文档和视图;</li>
<li><strong>db.collection.findOne()</strong>:查询指定集合中满足条件的第一个文档,并以格式化方式展现,通过<code>pretty()</code>方法。</li>
</ul>
<p>来自官方文档的测试数据:</p>
<pre><code class="language-javascript">db.inventory.insertMany([
   { item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
   { item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "A" },
   { item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },
   { item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },
   { item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" }
]);
</code></pre>
<h3 id="dbcollectionfind">db.collection.find()</h3>
<p><strong>db.collection.find()</strong>可以说是使用频率最高的方法了,可以用来查询数据库集合当中的文档。</p>
<p>语法格式如下:</p>
<pre><code class="language-javascript">db.collection.find(&lt;query&gt;, &lt;projection&gt;)
</code></pre>
<ul>
<li><strong>query</strong>:查询表达式;</li>
<li><strong>projection</strong>:指定查询结果集中需要显示的字段。
<ul>
<li>Col_name:1|true代表显示该字段;</li>
<li>Col_name:0 | false 代表不显示该字段。</li>
</ul>
</li>
</ul>
<p><code>_id</code>字段是默认显示的,如果不想显示,则显式指定<code>{"_id" : 0}</code>。</p>
<p>查询所有文档:</p>
<pre><code class="language-javascript">db.inventory.find()
</code></pre>
<p>或</p>
<pre><code class="language-javascript">db.inventory.find({})
</code></pre>
<h3 id="dbcollectionfindone">db.collection.findOne()</h3>
<p><strong>db.collection.findOne()</strong>方法显示符合条件查询的第一条文档,接受的参数与<strong>db.collection.find()</strong>方法一致。</p>
<h3 id="条件查询操作符">条件查询操作符</h3>
<p>通常对文档的查询,是需要带条件的,而很少使用到不带条件的全文档检索,以下总结了几种常使用的查询操作符:</p>
<h4 id="比较操作符">比较操作符</h4>
<p>比较操作符涉及的操作如下表所示:</p>
<table>
<thead>
<tr>
<th>名称</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td>$eq</td>
<td>与指定值相等</td>
</tr>
<tr>
<td>$gt</td>
<td>大于指定的值</td>
</tr>
<tr>
<td>$gte</td>
<td>大于或等于指定的值</td>
</tr>
<tr>
<td>$in</td>
<td>指定的值在数组中</td>
</tr>
<tr>
<td>$lt</td>
<td>小于指定的值</td>
</tr>
<tr>
<td>$lte</td>
<td>小于或等于指定的值</td>
</tr>
<tr>
<td>$ne</td>
<td>所有不等于指定的值</td>
</tr>
<tr>
<td>$nin</td>
<td>指定的值不在数组中</td>
</tr>
</tbody>
</table>
<p>使用示例:</p>
<pre><code class="language-javascript">// $eq:等值查询 SQL: SELECT * FROM inventory WHERE status = "D";
db.inventory.find( { status: "D" } )

// $ne 同$eq

// $gt:范围查询(以大于为例) SQL: SELECT * FROM inventory WHERE qty &gt; 30;
db.inventory.find( { qty: { $gt: 30 } } )

// $gte、$lt、$lte 同$gt

// $in:或查询,可使用or代替 SQL: SELECT * FROM inventory WHERE status in ("A", "D")
db.inventory.find( { status: { $in: [ "A", "D" ] } } )

// $nin 同$in
</code></pre>
<h4 id="逻辑操作符">逻辑操作符</h4>
<p>逻辑操作符涉及的操作如下表所示:</p>
<table>
<thead>
<tr>
<th>名称</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td>$and</td>
<td>指定查询同时满足多个条件查询子句</td>
</tr>
<tr>
<td>$not</td>
<td>指定查询不满足条件查询子句</td>
</tr>
<tr>
<td>$nor</td>
<td>指定查询无法满足多个条件查询子句</td>
</tr>
<tr>
<td>$or</td>
<td>指定查询满足其中某个条件查询子句</td>
</tr>
</tbody>
</table>
<p>使用示例:</p>
<pre><code class="language-js">// $and: 逻辑与查询 SQL: SELECT * FROM inventory WHERE status = "A" AND qty &lt; 30;
db.inventory.find( { $and: [ { status: { $eq: "A" },qty: { $lt: 30 } } ] } )

// $not: 不符合查询 SQL: SELECT * FROM inventory WHERE status &lt;&gt; "A";
db.inventory.find( { status: { $not: { $eq: "A" } } } )

/*
$nor: 无法同时满足多个条件查询,字段不存在时也符合 SQL: SELECT * FROM inventory WHERE status &lt;&gt; "A" AND qty &gt; 30;
符合以下条件之一都会出现在结果集中:
1.文档包含status和qty字段并且符合条件;
2.文档包含status字段并且符合条件,不包含qty字段;
3.文档不包含status字段,包含qty字段并且符合条件;
4.文档不包含status字段和qty字段。
*/
db.inventory.find( { $nor: [ { status: { $eq: "A" } },{ qty: { $lt: 30 } } ] } )

// $or: 逻辑或查询 SQL: SELECT * FROM inventory WHERE status = "A" OR qty &lt; 30;
db.inventory.find( { $or: [ { status: "A" }, { qty: { $lt: 30 } } ] } )
</code></pre>
<h4 id="元素操作符">元素操作符</h4>
<p>元素操作符主要涉及的操作如下表所示:</p>
<table>
<thead>
<tr>
<th>名称</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td>$exists</td>
<td>指定查询文档是否有对应的字段</td>
</tr>
<tr>
<td>$type</td>
<td>指定查询文档的某个字段是否是对应类型</td>
</tr>
</tbody>
</table>
<p>使用示例:</p>
<pre><code class="language-javascript">// $exists: 是否存在指定字段查询
db.inventory.find( { price: { $exists: true } } )

// $type: 字段是否是指定类型查询
db.inventory.find( { "qty": { $type: "double" } } )
</code></pre>
<h4 id="评估操作符">评估操作符</h4>
<p>评估操作符主要涉及的操作如下表所示,更多操作符可以参考官方文档:<strong>https://docs.mongodb.com/manual/reference/operator/query-evaluation/</strong>。</p>
<table>
<thead>
<tr>
<th>名称</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td>$expr</td>
<td>为同一个文档中的字段指定表达式并且符合条件的查询,比如比较同一文档当中两个字段的值</td>
</tr>
<tr>
<td>$mod</td>
<td>为字段值取模并且符合条件的查询</td>
</tr>
</tbody>
</table>
<p>为了更好的使用这两个主要的操作符,额外创建个文档:</p>
<pre><code class="language-javascript">db.monthlyBudget.insertMany([
    { "_id" : 1, "category" : "food", "budget": 400, "spent": 450 },
    { "_id" : 2, "category" : "drinks", "budget": 100, "spent": 150 },
    { "_id" : 3, "category" : "clothes", "budget": 100, "spent": 50 },
    { "_id" : 4, "category" : "misc", "budget": 500, "spent": 300 },
    { "_id" : 5, "category" : "travel", "budget": 200, "spent": 650 }
]);
</code></pre>
<p>使用示例:</p>
<pre><code class="language-javascript">// $expr: 允许使用聚合表达式,这里以$gt为例,更多表达式参考 https://docs.mongodb.com/manual/meta/aggregation-quick-reference/#aggregation-expressions
db.monthlyBudget.find( { $expr: { $gt: [ "$spent" , "$budget" ] } } )

// $mod: 对字段所在值进行取模运算,显示符合条件的查询,如qty字段值对4取模,并且余数为0
db.inventory.find( { qty: { $mod: [ 4, 0 ] } } )
</code></pre>
<h2 id="更新update-operations">更新(Update Operations)</h2>
<p>更新(Update Operations)是对已存在的文档进行修改操作,MongoDB提供以下几种主要更新文档方法:</p>
<ul>
<li><strong>db.collection.update()</strong>:更新或替换集合中符合条件的一个或多个文档;</li>
<li><strong>db.collection.updateOne()</strong>:只更新集合中符合条件的第一个文档,即使有多个文档(版本3.2新增);</li>
<li><strong>db.collection.updateMany()</strong>:更新集合中所有符合条件的文档(版本3.2新增)。</li>
</ul>
<h3 id="dbcollectionupdate">db.collection.update()</h3>
<p>根据<code>update</code>指定的表达式可以修改文档中符合条件的字段或代替整个文档。具体的语法格式如下:</p>
<pre><code class="language-javascript">db.collection.update(
   &lt;query&gt;,   //查询表达式
   &lt;update&gt;,//更新表达式
   {
   upsert: &lt;boolean&gt;,
   multi: &lt;boolean&gt;,
   writeConcern: &lt;document&gt;,
   collation: &lt;document&gt;,
   arrayFilters: [ &lt;filterdocument1&gt;, ... ],
   hint:&lt;document|string&gt;                   // 版本4.2新增
   }
)
</code></pre>
<p>参数说明:</p>
<ul>
<li>
<p><strong>query</strong>:更新文档的查询表达式;如果指定了参数<code>upsert: true</code>并且集合中没有符合查询条件的文档,查询条件中有关于字段<code>_id</code>指定了<code>.</code>分隔符的,并不会插入新的文档;</p>
</li>
<li>
<p><strong>update</strong>:主要包含三种格式</p>
<ul>
<li>1.更新文档:只包含更新操作符表达式;</li>
<li>2.替换文档:只包含<code>&lt;field1&gt;: &lt;value1&gt;</code>对;</li>
<li>3.聚合管道:版本4.2新增,详细参考官方文档。</li>
</ul>
</li>
<li>
<p><strong>upsert</strong>:当query查询条件没符合更新的文档,就新创建文档(可选),默认值为<strong>false</strong>;</p>
</li>
<li>
<p><strong>multi</strong>:是否更新多个符合条件的文档(可选),默认值为<strong>false</strong>,只更新符合条件的第一个文档;</p>
</li>
<li>
<p><strong>writeConcern</strong>:参考<strong>db.collection.insert()</strong>相同参数说明;</p>
</li>
<li>
<p><strong>collation</strong>:指定校对规则(可选,版本3.4新增);</p>
</li>
<li>
<p><strong>arrayFilters</strong>:文档数组更新过滤操作符(可选,版本3.6新增);</p>
<p>详细参考:<strong>https://docs.mongodb.com/manual/reference/method/db.collection.update/#specify-arrayfilters-for-array-update-operations</strong></p>
</li>
<li>
<p><strong>hint</strong>:采用文档或字符串的形式指定适用于查询表达式的索引,如果索引不存在则报错(可选,版本4.2新增)。</p>
</li>
</ul>
<p>使用示例:</p>
<p>使用示例将通过使用两种场景进行,一是没有使用参数选项<code>upsert</code>,二是使用参数选项<code>upsert</code>。</p>
<ul>
<li><strong>不使用选项upsert</strong></li>
</ul>
<pre><code class="language-javascript">// 测试数据
db.books.remove({});

db.books.insertMany([
{
    "_id" : 1,
    "item" : "TBD",
    "stock" : 0,
    "info" : { "publisher" : "1111", "pages" : 430 },
    "tags" : [ "technology", "computer" ],
    "ratings" : [ { "by" : "ijk", "rating" : 4 }, { "by" : "lmn", "rating" : 5 } ],
    "reorder" : false
   },
   {
    "_id" : 2,
    "item" : "XYZ123",
    "stock" : 15,
    "info" : { "publisher" : "5555", "pages" : 150 },
    "tags" : [ ],
    "ratings" : [ { "by" : "xyz", "rating" : 5 } ],
    "reorder" : false
   }
]);


/* 使用选项参数 upsert: true
1、如果查询表达式找到匹配的文档,则执行更新操作;
2、如果查询表达式没有找到匹配的文档,则执行插入操作;
*/
db.books.update(
   { item: "ZZZ135" },   // 查询表达式
   {                     // 更新或替换文档
   item: "ZZZ135",
   stock: 5,
   tags: [ "database" ]
   },
   { upsert: true }
);

// 1.使用更新操作表达式
/* $set操作符
1、查询表达式指定需要更新的文档 _id;
2、$inc操作符: stock的字段值+5;
3、$set操作符: 替换item字段值,替换嵌入文档info的publisher字段值,替换tags字段值,替换数组ratings的第二个元素值
*/
db.books.update(
   { _id: 1 },
   {
   $inc: { stock: 5 },
   $set: {
       item: "ABC123",
       "info.publisher": "2222",
       tags: [ "software" ],
       "ratings.1": { by: "xyz", rating: 3 }
   }
   }
);
更新之后的文档:
{

"_id" : 1,
"item" : "ABC123",
"stock" : 5,
"info" : { "publisher" : "2222", "pages" : 430 },
"tags" : [ "software" ],
"ratings" : [ { "by" : "ijk", "rating" : 4 }, { "by" : "xyz", "rating" : 3 } ],
"reorder" : false
}

// 2.为已存在的数组添加元素
// $push操作符: 为指定文档数组ratings添加一个元素
db.books.update(
   { _id: 2 },
   {
   $push: { ratings: { "by" : "jkl", "rating" : 2 } }
   }
);
更新之后的文档:
{
"_id" : 2,
"item" : "XYZ123",
"stock" : 15,
"info" : {
   "publisher" : "5555",
   "pages" : 150
},
"tags" : [ ],
"ratings" : [
   { "by" : "xyz", "rating" : 5 },

   { "by" : "jkl", "rating" : 2 }

],
"reorder" : false
}

// 3.文档移除字段
// $unset操作符: 移除文档的指定字段,为_id:1文档移除tags字段
db.books.update( { _id: 1 }, { $unset: { tags: 1 } } );
更新后的文档:
{
"_id" : 1,
"item" : "TBD",
"stock" : 0,
"info" : {
   "publisher" : "1111",
   "pages" : 430
},
"ratings" : [ { "by" : "ijk", "rating" : 4 }, { "by" : "lmn", "rating" : 5 } ],
"reorder" : false
}

// 4.替换整个文档
// 替换_id:2的文档
db.books.update(
   { _id: 2 },
   {
   item: "XYZ123",
   stock: 10,
   info: { publisher: "2255", pages: 150 },
   tags: [ "baking", "cooking" ]
   }
);
更新后的文档:
{
   "_id" : 2,
   "item" : "XYZ123",
   "stock" : 10,
   "info" : { "publisher" : "2255", "pages" : 150 },
   "tags" : [ "baking", "cooking" ]
}

// 5.更新多个文档
db.books.update(
   { stock: { $lte: 10 } },
   { $set: { reorder: true } },
   { multi: true }
);
更新后的全部文档:
[
{
    "_id" : 1,
    "item" : "ABC123",
    "stock" : 5,
    "info" : {
   "publisher" : "2222",
   "pages" : 430
    },
    "ratings" : [ { "by" : "ijk", "rating" : 4 }, { "by" : "xyz", "rating" : 3 } ],

    "reorder" : true

   }
   {
   "_id" : 2,
   "item" : "XYZ123",
   "stock" : 10,
   "info" : { "publisher" : "2255", "pages" : 150 },
   "tags" : [ "baking", "cooking" ],

   "reorder" : true

   }
]
</code></pre>
<ul>
<li><strong>使用upserts选项</strong></li>
</ul>
<pre><code class="language-javascript">/* 使用选项参数 upsert: true
1、如果查询表达式找到匹配的文档,则执行更新操作;
2、如果查询表达式没有找到匹配的文档,则执行插入操作;
*/

// 1.插入未符合更新条件的文档
db.books.update(
   { item: "ZZZ135" },   
   {                     
   item: "ZZZ135",
   stock: 5,
   tags: [ "database" ]
   },

   { upsert: true }      

);
因为集合并未满足条件的文档,则插入的文档为:
{
"_id" : ObjectId("5da78973835b2f1c75347a83"),
"item" : "ZZZ135",
"stock" : 5,
"tags" : [ "database" ]
}

// 2.插入未符合更新条件并且基于更新操作符的文档
// 如果没有符合更新查询条件,并且使用的是更新操作符,则会基于当前的查询条件和更新操作符字段插入新的文档
db.books.update(
   { item: "BLP921" },   
   {                     
      $set: { reorder: false },
      $setOnInsert: { stock: 10 }
   },
   { upsert: true }      
);
新插入的文档为:
{
"_id" : ObjectId("5da79019835b2f1c75348a0a"),
"item" : "BLP921",
"reorder" : false,
"stock" : 10
}

// 3.插入未符合更新条件并且基于聚合管道的文档
// 关于聚合管道请参考官方文档:https://docs.mongodb.com/manual/reference/method/db.collection.update/#update-with-aggregation-pipeline

// 4.插入未符合更新条件并且同时联合多文档操作符的文档
如果不符合查询条件,则只会插入单个文档
db.books.update(
{ "info.publisher": "Self-Published" },   
{                                       
    $set: { reorder: false, tags: [ "literature", "hardcover" ], stock: 25 }
},
{ upsert: true, multi: true }            
);
新插入的文档:
{
"_id" : ObjectId("5db337934f670d584b6ca8e0"),
"info" : { "publisher" : "Self-Published" },
"reorder" : false,
"stock" : 25,
"tags" : [ "literature", "hardcover" ]
}
</code></pre>
<h3 id="dbcollectionupdateone">db.collection.updateOne()</h3>
<p>根据<code>update</code>指定的参数可以修改文档中符合条件的字段或代替整个文档,与<strong>db.collection.update()</strong>不同的是每次只更新单个文档。</p>
<p>语法格式如下:</p>
<pre><code class="language-javascript">db.collection.updateOne(
   &lt;filter&gt;,
   &lt;update&gt;,
   {
   upsert: &lt;boolean&gt;,
   writeConcern: &lt;document&gt;,
   collation: &lt;document&gt;,
   arrayFilters: [ &lt;filterdocument1&gt;, ... ],
   hint:&lt;document|string&gt;      
   }
)
</code></pre>
<p>参数说明:</p>
<p>参考<strong>db.collection.update()</strong>的参数说明。</p>
<p>使用示例:</p>
<pre><code class="language-javascript">// 参考db.collection.update()
</code></pre>
<h3 id="dbcollectionupdatemany">db.collection.updateMany()</h3>
<p>根据<code>update</code>指定的参数可以修改文档中符合条件的字段或代替整个文档,与<strong>db.collection.updateOne()</strong>不同的是更新所有符合条件的文档。</p>
<p>语法格式如下:</p>
<pre><code class="language-javascript">db.collection.updateMany(
   &lt;filter&gt;,
   &lt;update&gt;,
   {
   upsert: &lt;boolean&gt;,
   writeConcern: &lt;document&gt;,
   collation: &lt;document&gt;,
   arrayFilters: [ &lt;filterdocument1&gt;, ... ],
   hint:&lt;document|string&gt;      
   }
)
</code></pre>
<p>参数说明:</p>
<p>参考db.collection.update()的参数说明。</p>
<p>使用示例:</p>
<pre><code class="language-javascript">// 参考db.collection.update()
</code></pre>
<h2 id="删除delete-operations">删除(Delete Operations)</h2>
<p>删除是指对集合当中已存在的文档进行清除操作,MongoDB提供以下几种主要删除文档方法:</p>
<ul>
<li><strong>db.collection.deleteOne()</strong>:只删除集合中符合条件的一个文档;</li>
<li><strong>db.collection.deleteMany()</strong>:删除集合中所有符合条件的文档;</li>
<li><strong>db.collection.remove()</strong>:删除集合中符合条件的一个或多个文档。</li>
</ul>
<h3 id="dbcollectiondeleteone">db.collection.deleteOne()</h3>
<p>根据<code>filter</code>选项条件删除集合中的单个文档,具体语法格式如下:</p>
<pre><code class="language-javascript">db.collection.deleteOne(
   &lt;filter&gt;,
   {
      writeConcern: &lt;document&gt;,
      collation: &lt;document&gt;
   }
)
</code></pre>
<p>参数说明:</p>
<ul>
<li><strong>filter</strong>:指定基于查询表达式的过滤条件,关于查询表达式可以查看<code>db.collecion.find()</code>中的<code>&lt;query&gt;</code>;</li>
<li><strong>writeConcern</strong>:参考<strong>db.collection.insert()</strong>相同参数说明;</li>
<li><strong>collation</strong>:指定校对规则(可选,版本3.4新增);</li>
</ul>
<p>使用示例:</p>
<pre><code class="language-javascript">// 删除指定条件的单个文档
db.orders.deleteOne( { "_id" : 1 } );
{ "acknowledged" : true, "deletedCount" : 1 }
</code></pre>
<h3 id="dbcollectiondeletemany">db.collection.deleteMany()</h3>
<p>根据<code>filter</code>选项条件删除集合中的单个文档,具体语法格式如下:</p>
<pre><code class="language-javascript">db.collection.deleteMany(
   &lt;filter&gt;,
   {
      writeConcern: &lt;document&gt;,
      collation: &lt;document&gt;
   }
)
</code></pre>
<p>参数说明:</p>
<p>参考<strong>db.collection.deleteOne()</strong>的参数说明。</p>
<p>使用示例:</p>
<pre><code class="language-javascript">// 删除指定条件的多个文档
db.orders.deleteMany( {"cust_id" : "Cam Elot"} );
{ "acknowledged" : true, "deletedCount" : 2 }
</code></pre>
<blockquote>
<p>注意: 如果是对固定集合进行删除文档操作则会报错,固定集合的清除操作使用方法<strong>db.collection.drop()</strong>。</p>
</blockquote>
<h2 id="总结">总结</h2>
<ol>
<li>本文简单梳理了在Mongo Shell下基本的CRUD操作,主要适用于DBA的运维管理,如果是研发同学,根据不同的编程语言使用不同客户端驱动进行操作,详细同样可以参考官方文档;</li>
<li>针对CRUD各个方面还有其他一些额外的方法,比如查询修改文档方法<strong>db.collection.findAndModify()</strong>,这里只是总结每个文档操作中一些最基础的方法,对于额外高级的方法这里不再赘述;</li>
<li>掌握了这些基本的CRUD操作,就可以对MongoDB文档进行操作了,但还是需要控制好权限,毕竟数据安全不是小事,做变更之前做好数据的备份,以防万一。</li>
</ol>
<h2 id="参考">参考</h2>
<p><strong>https://docs.mongodb.com/manual/crud/</strong></p>
<p><strong>https://docs.mongodb.com/manual/reference/operator/query-evaluation/</strong> </p>
<p><strong>https://docs.mongodb.com/manual/reference/method/db.collection.update/#specify-arrayfilters-for-array-update-operations</strong></p>
<p><strong>https://docs.mongodb.com/manual/reference/method/db.collection.update/#update-with-aggregation-pipeline</strong></p>
<p><strong>☆〖本人水平有限,文中如有错误还请留言批评指正!〗☆</strong></p>


</div>
<div id="MySignature" role="contentinfo">
    <div id="dbabdSignature">   
      <div>作者:H_Johnny</div>
      <div>出处:http://www.cnblogs.com/dbabd/</div>
      <div>本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接。</div>
      <div>如果您觉得文章不错,请帮忙点击右下角的推荐,谢谢!
    </div></div><br><br>
来源:https://www.cnblogs.com/dbabd/p/13045006.html
頁: [1]
查看完整版本: MongoDB 4.X CRUD基本操作