MongoDB 4.X CRUD basic operating instructions

Introduction: This article summarizes mongodb 4 Some basic addition, deletion, modification and query operations of documents involved in X in mongo shell client, namely CRUD operation.


For image download, domain name resolution and time synchronization, please click Alibaba open source mirror station

1, Create operations

Create operations are also called insert operations. When the collection does not exist, the insert operation will also create the collection. MongoDB provides the following methods for inserting documents:

  • db.collection.insert(): inserts one or more documents into the specified collection.
  • db.collection.insertOne(): inserts a single document into the specified collection (new in version 3.2).
  • db.collection.insertMany(): inserts multiple documents into the specified collection (new in version 3.2).

1. db.collection.insert()

In normal use, DB collection. Insert () is the most frequently used document insertion method. The specific syntax format is as follows:

db.collection.insert(
   <document or array of documents>,
   {
     writeConcern: <document>,
     ordered: <boolean>
   }
)

Parameter Description:

  • document: specify one or more documents;
  • writeConcern: document write confirmation level (optional). The confirmation level of read-write policy will be discussed later;
  • ordered: Specifies whether documents are inserted in order (optional). The default value is true;

    • When it is specified as true, when inserting multiple documents, the documents will be sorted and saved in an array for insertion. If one of the documents fails to be inserted, the remaining documents in the array will not be inserted;
    • When false is specified, when inserting multiple documents, the documents will not be sorted and saved in an array for insertion. If one of the documents fails to be inserted, the insertion operation of the remaining documents in the array will not be affected.

If not specified in the inserted document_ ID field, MongoDB will automatically generate a field with unique ObjectId value for the document_ id.
Use example:

// Not specified_ Insert single document with id field
db.products.insert( { item: "card", qty: 15 } );
// Designate_ Insert single document with id field
db.products.insert( { _id: 10, item: "box", qty: 20 } );
// Insert multiple documents without sorting. Multiple documents are included in array []
db.products.insert(
   [
     { _id: 11, item: "pencil", qty: 50, type: "no.2" },
     { item: "pen", qty: 20 },
     { item: "eraser", qty: 25 }
   ]
);
// Insert multiple documents and sort them
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 }
);

2. db.collection.insertOne()

The syntax format is as follows:

db.collection.insertOne(
   <document>,
   {
      writeConcern: <document>
   }
)

Parameter Description: refer to DB collection. Parameter description of insert().
Use example:

// Inserting documents in a single line, about_ Whether the id field is specified or not is also related to DB collection. Insert() consistent
db.products.insertOne( { item: "card", qty: 15 } );

3. db.collection.insertMany()

The syntax format is as follows:

db.collection.insertMany(
   [ <document 1> , <document 2>, ... ],
   {
      writeConcern: <document>,
      ordered: <boolean>
   }
)

Parameter Description: refer to DB collection. Parameter description of insert().
Usage example: refer to DB collection. Parameter description of insert().

4. Return confirmation information

db. collection. The information returned by insert() after the document is successfully inserted is relatively concise:

db.products.insert( { item: "card", qty: 15 } );
WriteResult({ "nInserted" : 1, "writeConcernError" : [ ] })

db.collection.insertOne() and DB collection. The information returned by insertmany() is more detailed:

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
    ]
}

2, Query (Read Operations)

Read operations is to query the existing documents in the collection, that is, the select operation in the corresponding relational database, such as MySQL and MongoDB. MongoDB provides the following main methods to query documents:

  • db.collection.find(): query one or more documents and views that meet the conditions in the specified set;
  • db.collection.findOne(): query the first document in the specified set that meets the conditions and present it in a formatted manner through the pretty() method.

Test data from official documents:

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" }
]);

1. db.collection.find()

db.collection.find() can be said to be the most frequently used method, which can be used to query the documents in the database collection.
The syntax format is as follows:

db.collection.find(<query>, <projection>)
  • Query: query expression;
  • projection: Specifies the fields to be displayed in the query result set.

    • Col_name:1 | true means to display this field;
    • Col_name:0 | false means that the field is not displayed.

_ The ID field is displayed by default. If you don't want to display it, explicitly specify {"_id": 0}.
Query all documents:

db.inventory.find()

or

db.inventory.find({})

2. db.collection.findOne()

db. collection. The findone () method displays the first document of the qualified query, and the accepted parameters are the same as dB collection. The find () method is consistent.

3. Conditional query operator

In general, queries on documents need to be conditional, but full-text file retrieval without conditions is rarely used. The following summarizes several commonly used query operators:

Comparison operator

The operations involved in the comparison operator are shown in the following table:

nameexplain
$eqEqual to the specified value
$gtGreater than the specified value
$gteGreater than or equal to the specified value
$inThe specified value is in the array
$ltLess than the specified value
$lteLess than or equal to the specified value
$neAll are not equal to the specified value
$ninThe specified value is not in the array

Use example:

// $eq: equivalent query SQL: SELECT * FROM inventory WHERE status = "D";
db.inventory.find( { status: "D" } )
// $ne is the same as $eq
// $gt: range query (taking greater than as an example) SQL: select * from inventory where qty > 30;
db.inventory.find( { qty: { $gt: 30 } } )
// $gte, $lt and $lte are the same as $gt
// $in: or query, or can be used instead of SQL: SELECT * FROM inventory WHERE status in ("A", "D")
db.inventory.find( { status: { $in: [ "A", "D" ] } } )
// $nin is the same as $in

Logical operator

The operations involved in logical operators are shown in the following table:

nameexplain
$andSpecifies that the query satisfies multiple conditional query clauses at the same time
$notThe specified query does not satisfy the conditional query clause
$norThe specified query cannot satisfy more than one conditional query clause
$orSpecifies that the query satisfies one of the criteria query clauses

Use example:

// $and: logic and query SQL: select * from inventory where status = "a" and qty < 30;
db.inventory.find( { $and: [ { status: { $eq: "A" },  qty: { $lt: 30 } } ] } )
// $not: non compliant query SQL: select * from inventory where status < > "a";
db.inventory.find( { status: { $not: { $eq: "A" } } } )
/*
$nor: Multiple conditional queries cannot be satisfied at the same time. If the field does not exist, it also meets SQL: select * from inventory where status < > "a" and qty > 30; 
Any of the following conditions will appear in the result set:
1.The document contains status and qty fields and meets the conditions;
2.The document contains the status field and meets the conditions, but does not contain the qty field;
3.The document does not contain the status field, but contains the qty field and meets the conditions;
4.The document does not contain status and qty fields.
*/
db.inventory.find( { $nor: [ { status: { $eq: "A" } },  { qty: { $lt: 30 } } ] } )
// $or: logical or query SQL: select * from inventory where status = "a" or qty < 30;
db.inventory.find( { $or: [ { status: "A" }, { qty: { $lt: 30 } } ] } )

Element operator

The main operations involved in the element operator are shown in the following table:

nameexplain
$existsSpecifies whether the query document has corresponding fields
$typeSpecifies whether a field in the query document is the corresponding type

Use example:

// $exists: does the specified field query exist
db.inventory.find( { price: { $exists: true } } )
// $type: whether the field is the specified type query
db.inventory.find( { "qty": { $type: "double" } } )

Evaluation operator

The main operations involved in the evaluation operator are shown in the following table. For more operators, please refer to the official documents: Evaluation Query Operators — MongoDB Manual.

nameexplain
$exprQueries that specify expressions for fields in the same document and meet the conditions, such as comparing the values of two fields in the same document
$modA query that takes a module for the field value and meets the criteria

To make better use of these two main operators, create an additional document:

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 }
]);

Use example:

// $expr: aggregate expressions are allowed. Here, $gt is taken as an example. For more expressions, please refer to https://docs.mongodb.com/manual/meta/aggregation-quick-reference/#aggregation-expressions
db.monthlyBudget.find( { $expr: { $gt: [ "$spent" , "$budget" ] } } )
// $mod: modulo the value of the field and display the qualified query. For example, the value of the qty field modulo 4 and the remainder is 0
db.inventory.find( { qty: { $mod: [ 4, 0 ] } } )

3, Update operations

Update operations is to modify existing documents. MongoDB provides the following main methods to update documents:

  • db.collection.update(): update or replace one or more documents that meet the conditions in the collection;
  • db.collection.updateOne(): update only the first document in the set that meets the conditions, even if there are multiple documents (new in version 3.2);
  • db.collection.updateMany(): updates all eligible documents in the collection (new in version 3.2).

1. db.collection.update()

According to the expression specified by update, you can modify the qualified fields in the document or replace the whole document. The specific syntax format is as follows:

db.collection.update(
   <query>,   //Query expression
   <update>,  //Update expression
   {
     upsert: <boolean>,
     multi: <boolean>,
     writeConcern: <document>,
     collation: <document>,
     arrayFilters: [ <filterdocument1>, ... ],
     hint:  <document|string>                   // New in version 4.2
   }
)

Parameter Description:

  • Query: update the query expression of the document; If the parameter upsert: true is specified and there are no documents matching the query criteria in the collection, there are fields in the query criteria_ id specified Separator, and no new document will be inserted;
  • update: it mainly contains three formats

    • 1. Update document: contains only the update operator expression;
    • 2. Replacement documents: only contain < field1 >: < value1 > pairs;
    • 3. Polymerization pipeline: added in version 4.2. Please refer to the official documents for details.
  • upsert: when the query criteria do not meet the updated document, a new document is created (optional). The default value is false;
  • multi: whether to update multiple qualified documents (optional). The default value is false. Only the first qualified document will be updated;
  • writeConcern: reference dB collection. Insert() same parameter description;
  • Collation: Specifies the collation rule (optional, added in version 3.4);
  • arrayFilters: document array update filter operator (optional, new in version 3.6);
    Detailed reference: db.collection.update() — MongoDB Manual
  • hint: specify the index applicable to the query expression in the form of document or string. If the index does not exist, an error will be reported (optional, new in version 4.2).

Use example:
The usage example will be carried out by using two scenarios: one is not using the parameter option upsert, and the other is using the parameter option upsert.

  • Do not use option upsert
// test data
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
   }
]);
/* Use option parameter upsert: true
1,If the query expression finds a matching document, the update operation is performed;
2,If the query expression does not find a matching document, execute the insertion operation;
*/
db.books.update(
   { item: "ZZZ135" },   // Query expression
   {                     // Update or replace documents
     item: "ZZZ135",
     stock: 5,
     tags: [ "database" ]
   },
   { upsert: true }
);
// 1. Use update operation expression
/* $set Operator
1,The query expression specifies the document to be updated_ id;
2,$inc Operator: field value of stock + 5;
3,$set Operators: replace the item field value, replace the publisher field value embedded in the document info, replace the tags field value, and replace the second element value of the array ratings
*/
db.books.update(
   { _id: 1 },
   {
     $inc: { stock: 5 },
     $set: {
       item: "ABC123",
       "info.publisher": "2222",
       tags: [ "software" ],
       "ratings.1": { by: "xyz", rating: 3 }
     }
   }
);
Updated document:
{
  "_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. Add elements to the existing array
// $push operator: adds an element to the specified document array ratings
db.books.update(
   { _id: 2 },
   {
     $push: { ratings: { "by" : "jkl", "rating" : 2 } }
   }
);
Updated document:
{
  "_id" : 2,
  "item" : "XYZ123",
  "stock" : 15,
  "info" : {
   "publisher" : "5555",
   "pages" : 150
  },
  "tags" : [ ],
  "ratings" : [
   { "by" : "xyz", "rating" : 5 },
   { "by" : "jkl", "rating" : 2 }
  ],
  "reorder" : false
 }
// 3. Remove field from document
// $unset operator: removes the specified field of the document, which is_ id:1 remove tags field from document
db.books.update( { _id: 1 }, { $unset: { tags: 1 } } );
Updated document:
{
  "_id" : 1,
  "item" : "TBD",
  "stock" : 0,
  "info" : {
   "publisher" : "1111",
   "pages" : 430
  },
  "ratings" : [ { "by" : "ijk", "rating" : 4 }, { "by" : "lmn", "rating" : 5 } ],
  "reorder" : false
 }
// 4. Replace the entire document
// Replace_ Document with id: 2
db.books.update(
   { _id: 2 },
   {
     item: "XYZ123",
     stock: 10,
     info: { publisher: "2255", pages: 150 },
     tags: [ "baking", "cooking" ]
   }
);
Updated document:
{
   "_id" : 2,
   "item" : "XYZ123",
   "stock" : 10,
   "info" : { "publisher" : "2255", "pages" : 150 },
   "tags" : [ "baking", "cooking" ]
}
// 5. Update multiple documents
db.books.update(
   { stock: { $lte: 10 } },
   { $set: { reorder: true } },
   { multi: true }
);
All updated documents:
[
  {
    "_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
   }
]
  • Using the upserts option
/* Use option parameter upsert: true
1,If the query expression finds a matching document, the update operation is performed;
2,If the query expression does not find a matching document, execute the insertion operation;
*/
// 1. Insert documents that do not meet the update conditions
db.books.update(
   { item: "ZZZ135" },   
   {                     
     item: "ZZZ135",
     stock: 5,
     tags: [ "database" ]
   },
   { upsert: true }      
);
Because the collection does not meet the criteria, the inserted document is:
{
  "_id" : ObjectId("5da78973835b2f1c75347a83"),
  "item" : "ZZZ135",
  "stock" : 5,
  "tags" : [ "database" ]
}
// 2. Insert a document that does not meet the update conditions and is based on the update operator
// If the update query criteria are not met and the update operator is used, a new document will be inserted based on the current query criteria and update operator fields
db.books.update(
   { item: "BLP921" },   
   {                     
      $set: { reorder: false },
      $setOnInsert: { stock: 10 }
   },
   { upsert: true }      
);
The newly inserted document is:
{
  "_id" : ObjectId("5da79019835b2f1c75348a0a"),
  "item" : "BLP921",
  "reorder" : false,
  "stock" : 10
}
// 3. Insert a document that does not meet the update criteria and is based on the aggregation pipeline
// For polymerization pipeline, please refer to the official document: https://docs.mongodb.com/manual/reference/method/db.collection.update/#update-with-aggregation-pipeline
// 4. Insert documents that do not meet the update conditions and combine multiple document operators at the same time
 If the query criteria are not met, only a single document will be inserted
db.books.update(
  { "info.publisher": "Self-Published" },   
  {                                         
    $set: { reorder: false, tags: [ "literature", "hardcover" ], stock: 25 }
  },
  { upsert: true, multi: true }             
);
Newly inserted document:
{
  "_id" : ObjectId("5db337934f670d584b6ca8e0"),
  "info" : { "publisher" : "Self-Published" },
  "reorder" : false,
  "stock" : 25,
  "tags" : [ "literature", "hardcover" ]
}

2. db.collection.updateOne()

According to the parameters specified in update, you can modify the qualified fields in the document or replace the whole document, which is the same as dB collection. Update () is different in that only a single document is updated at a time.
The syntax format is as follows:

db.collection.updateOne(
   <filter>,
   <update>,
   {
     upsert: <boolean>,
     writeConcern: <document>,
     collation: <document>,
     arrayFilters: [ <filterdocument1>, ... ],
     hint:  <document|string>        
   }
)

Parameter Description:
Reference dB collection. Parameter description of update().
Use example:

// Reference dB collection. update()

3. db.collection.updateMany()

According to the parameters specified in update, you can modify the qualified fields in the document or replace the whole document, which is the same as dB collection. The difference with updateone() is that it updates all documents that meet the criteria.
The syntax format is as follows:

db.collection.updateMany(
   <filter>,
   <update>,
   {
     upsert: <boolean>,
     writeConcern: <document>,
     collation: <document>,
     arrayFilters: [ <filterdocument1>, ... ],
     hint:  <document|string>        
   }
)

Parameter Description:
Reference dB collection. Parameter description of update().
Use example:

// Reference dB collection. update()

4, Delete operations

Deleting refers to clearing the existing documents in the collection. MongoDB provides the following main methods to delete documents:

  • db.collection.deleteOne(): delete only one qualified document in the collection;
  • db.collection.deleteMany(): deletes all qualified documents in the collection;
  • db. collection. Remove: remove one or more documents in the collection that meet the criteria.

1. db.collection.deleteOne()

Delete a single document in the collection according to the filter option conditions. The specific syntax format is as follows:

db.collection.deleteOne(
   <filter>,
   {
      writeConcern: <document>,
      collation: <document>
   }
)

Parameter Description:

  • Filter: specify the filter conditions based on query expressions. You can view dB. For query expressions collecion. < query > in find();
  • writeConcern: reference dB collection. Insert() same parameter description;
  • Collation: Specifies the collation rule (optional, added in version 3.4);

Use example:

// Delete a single document with specified criteria
db.orders.deleteOne( { "_id" : 1 } );
{ "acknowledged" : true, "deletedCount" : 1 }

2. db.collection.deleteMany()

Delete a single document in the collection according to the filter option conditions. The specific syntax format is as follows:

db.collection.deleteMany(
   <filter>,
   {
      writeConcern: <document>,
      collation: <document>
   }
)

Parameter Description: refer to DB collection. Parameter description of deleteone().
Use example:

// Delete multiple documents with specified criteria
db.orders.deleteMany( {"cust_id" : "Cam Elot"} );
{ "acknowledged" : true, "deletedCount" : 2 }

Note: if you delete a document from a fixed set, an error will be reported. The method of clearing a fixed set is dB collection. drop().

5, Summary

  1. This paper briefly combs the basic CRUD operation under Mongo Shell, which is mainly applicable to the operation and maintenance management of DBA. If you are a R & D student, you can use different client drivers according to different programming languages. For details, you can also refer to the official documents;
  2. There are other additional methods for all aspects of CRUD, such as query and modify document method dB collection. Findandmodify(), here is just a summary of some of the most basic methods in each document operation, and the additional advanced methods will not be repeated here;
  3. After mastering these basic CRUD operations, you can operate the MongoDB document, but you still need to control the permissions. After all, data security is not a trivial matter. Backup the data before making changes, just in case.

From this article: MongoDB 4. Basic operating instructions for X crud - Alibaba cloud developer community

Keywords: Database MongoDB

Added by JStefan on Sat, 12 Feb 2022 15:41:06 +0200