This is the 10th day of my participation in the August More text Challenge. For details, see: August More Text Challenge

Insert data

1.1 Inserting a Single Document

1.1.1 insert function

Syntax format: db.collectionName.insert(document)

  • dbIs the database of the current operation
  • collectionNameIs a collection of operations, none of which are automatically created
  • Insert document if not_idProperty is automatically created

For example, insert a single document under the User collection

db.user.insert({name:"ljc",love:["soccer","music"]})
Copy the code

The results in the visualization tool, on the command line results are consistent!

1.1.2 insertOne function

In versions after MongoDB3.2, insertOne() is provided to insert documents, and save is deprecated, so it is not learned, it is used in the same way as insert

Db.collection_name insertOne(document)

For example, insert a single document under the User collection

db.user.insertOne({name:"ddd",love:["play game","running"]})
Copy the code

The results in the visualization tool, on the command line results are consistent!

1.2 Inserting Multiple Documents

When you batch insert multiple documents into a collection, you need to use an array to hold the documents

1.2.1 insert function

Db.collection_name. Insert ([{},{},{}…]) )

For example, use insert to batch insert people information into users

Db. User. Insert ([{name: "zhang", the age: "18"}, {name: "bill", the age: "19"}])Copy the code

1.2.2 insertMany function

Syntax format: db.collection_name. InsertMany ([{},{},{}… )

For example, insertMany is used to batch insert people information into users

Db. User. InsertMany ([{name: "detective", the age: "28"}, {name: "six tang", the age: "29"}])Copy the code

1.3 tips

db.COLLECTION_NAME.insertOne(document)
db.COLLECTION_NAME.insertMany(document)
db.COLLECTION_NAME.replaceOne(document)
Copy the code

Parameters that

  1. document: Indicates the document to be written
  2. writeConcern: Indicates the write policy. The default value is 1, indicating that the write operation is required. 0 indicates that the write operation is not required
  3. ordered: Specifies whether to write sequentially. The default is true. Write sequentially

2. Update the document

MongoDB updates documents in the collection through the update function or save function.

2.1 the update function

The update() function is used to update existing documents.

The syntax format is:

db.COLLECTION_NAME.update(query,update,options)
Copy the code
  1. query : updateIs used to select the data to be updated
  2. update:updateAnd some newer operators
  3. upsert: Specifies whether to insert new data into the set if there is no data to update. The parameter value istrueorfalse, the default value isfalseAnd don’t insert
  4. multi: Specifies whether to update data in batches. This parameter indicates whether to update all data or only the first data when multiple data matching the query conditions are found. The default value isfalse
  5. writeConcern: An optional parameter that specifies the level at which an exception is thrown

In field

First we insert some data under the user set

db.user.insertMany([{title:"html",page:300},{title:"css",page:300},{title:"js",page:200},{title:"ts",page:250},{title:"w ebpack",page:220}])Copy the code

Insert the success

Next we update the data in the collection

First requirement: change the HTML page to 500

db.user.update({title:"html"},{title:"html",page:500})
Copy the code

Note: Updating a document is an operation to update the entire document. Even if only one value needs to be changed, all other attributes need to be written down, otherwise other attributes will be deleted

Second requirement: change all pages from 200 to 400

db.user.update({page:200},{$set:{page:400}},{multi:true})
Copy the code

Operating results

The $set operator is used above to update only one attribute in the data

2.2 updateOne and updateMany

Db.collection.updateone () updates a single document to the specified collection

Db.collection.updatemany () updates multiple documents to a specified collection

2.3 Update Operators

2.3.1 The $set operator

Used to specify a key and update the key value, created if the key does not exist. That is, we can use this operator to specify the properties we want to change without updating the entire document

Db.collection_name. Update ({query condition},{update operator :{update content}})

Change HTML to HTML5

db.user.update({title:"html"},{$set:{title:"html5"}});
Copy the code

This allows us to modify some data in the found document without deleting other data

If the data is not found, create new data

2.3.2 The $inc operator

In the document to meet the requirements of the numeric value to increase or decrease operation, regular increase, negative will decrease

db.user.updateOne({title:"js"},{$inc:{page:-20}})
Copy the code

Subtracting 20 from the page property of the data whose title is js

2.3.3 the $unset operator

It is used to delete the key, leaving its value null. When writing a command, change the value of the data in $unset to any value, whatever value is given is deleted.

Delete HTML page

db.user.update({title:"html"},{$unset:{page:"aaaa"}});
Copy the code

2.3.4 the $push operator

Insert a point here: if we need to change all of the data, our query property will fill in {}, which is to find all

Adds an array element to the key of an array type in the document, without filtering duplicate data. If the key does not exist, an array key is created

Add an auth field with the value LJC to all documents

db.user.update({},{$push:{auth:"ljc"}},{multi:true});
Copy the code

It looks like it was added successfully. Remember, array, array, array!

2.3.5 $pop operator

The value can only be 1 or -1. 1 indicates that the tail is deleted, and -1 indicates that the head is deleted

First of all, let’s push to enrich the array by adding an extra auth to the HTML

db.user.update({title:"html"},{$push:{auth:"htmlauth"}});
Copy the code

Next, we demonstrate the POP operation, which removes the first value of an auth array in HTML

db.user.update({title:"html"},{$pop:{auth:-1}})
Copy the code

2.3.6 Pull operator

Remove elements from the array that meet the criteria, as long as the criteria are met

Delete LJC from auth array

db.user.update({title:"js"},{$pull:{auth:"ljc"}})
Copy the code

2.3.7 pullAll operator

You can delete multiple values from an array at the same time

Delete LJC and CCC from auth in TS

db.user.update({title:"ts"},{$pullAll:{auth:["ljc","ccc"]});
Copy the code

2.3.8 The rename operator

Rename the key. Any type of key can be renamed

Change all title attribute names to name

db.user.update({},{$rename:{title:"name"}},{multi:true})
Copy the code

Success will be changed to name

Delete the document

3.1 remove the function

Syntax format:

db.user.remove(<query>,{justOne:<boolean>})
Copy the code

Parameter description:

  • query: A document condition that is optional for deletion
  • justOne: Deletes multiple or one documents.trueJust delete one,falseDelete all matching data

Delete documents whose name value is HTML

db.user.remove({name:"html"},{justOne:true})
Copy the code

Deleted successfully

Delete all data

db.user.remove({})
Copy the code

Note: Remove enrichment does not actually free space, and db.repairDatabase() needs to be executed to reclaim disk space

3.2 deleteOne function

This method removes only the first document that meets the condition, which is much simpler than remove

Delete the js

db.user.deleteOne({name:"js"})
Copy the code

3.3 deleteMany function

Delete all documents that meet the criteria

Delete all documents with page 200

db.user.deleteMany({page:200})
Copy the code

4. Query documents

The find function is used to query documents

Syntax format

db.collection.find(query, projection)
Copy the code
  • query: Specifies search conditions. This parameter is optional
  • projection: Optional, use the projection operator to specify the returned key

** Note: ** data can be read in a readable way by using the db.collection.find().pretty() method

You can also use the findOne method to return a document

4.1 Querying All Information

Query all documents

db.user.find({})
Copy the code

Deweighting by name

db.user.distinct("name")
Copy the code

Note: Methods used in MongoDB usually start with a $sign

4.2 Conditional Operators

The conditional operator is used to compare two expressions and get the data from the collection

Syntax format: find({key :{operator: condition}})

findOne

2 $eq

Equal operator

Query all document objects with page 300

db.user.find({page:{$eq:300}})
Copy the code

4.2.2 $lt

Less than operator

Example Query document objects whose page is less than 300

db.user.find({page:{$lt:300}})
Copy the code

Holdings of $lte

The less than or equal operator

Query document objects whose page is less than or equal to 300

db.user.find({page:{$lte:300}})
Copy the code

4.2.4 $gt

Greater than operator

Query document objects whose page is greater than 250

db.user.find({page:{$gt:250}})
Copy the code

4.2.5 $gte

The greater than or equal operator

Query document objects whose page is greater than or equal to 300

db.user.find({page:{$gte:300}})
Copy the code

4.2.6 $ne

Not equal operator

Query document objects whose page is not equal to 300

db.user.find({page:{$ne:300}})
Copy the code

4.2.7 $in

Multi-condition query, as long as satisfies one of the conditions in, can be queried

Query document objects with pages 220 and 300

The db. The user. The find ({page: {$in: [300220]}})Copy the code

Note: the value after $in is an array type!!

4.2.8 $nin

In contrast to in, everything except in is queried

Query document objects whose pages are not 220 and 300

The db. The user. The find ({page: {$nin: [300220]}})Copy the code

4.2.9 $and

Finds a document object that satisfies multiple criteria simultaneously

Syntax format:

Db.col. find({$and:[{$and}},{,}},...] })Copy the code

Query a document with page 300 and name value node

db.user.find({$and:[{name:"node"},{page:300}]})
Copy the code

When multiple query conditions are specified at the same time, the default is parallel, so we can write directly

db.user.find({name:"node"},{page:300})
Copy the code

4.2.10 $or

Queries document objects that meet at least one of the criteria

Query a document whose page is 300 or whose name is node

db.user.find({$or:[{name:"node"},{page:300}]})
Copy the code

4.2.11 $type operator

Query by value type

Example Query the value whose type is “page” and “number”

db.user.find({page:{$type:"number"}})
Copy the code

The data types are as follows, from the novice tutorial

This can be specified using a number corresponding to the type

Db. Col. Find ({" title ": {$type: 2}}) is equivalent to the col. Find ({" title" : {$type: 'string'}})Copy the code

4.3 Regular Query

Use regular expressions to query documents of a particular format

Example Query a case-insensitive document whose name ends in s

db.user.find({name:/s$/i})
Copy the code

4.4 Projection Query

Select only part of the data in the document, not the entire document

To limit the default display of all fields in a document in the find() method, set the field list value to 0 or 1

Only the name value is displayed, and the _ID value is not displayed

db.user.find({},{_id:0,name:1})
Copy the code

Display name and page

db.user.find({},{page:1,name:1})
Copy the code

Note: the _id field exists by default!!

Name and page are not displayed

db.user.find({},{page:0,name:0})
Copy the code

Note: The value of the attribute can be different only if the value of the attribute is set to 0. In other words, the value of the attribute cannot be set to 1 and 0 at the same time

Such as:

db.user.find({},{_id:0,page:1,name:0})
Copy the code

An error

4.5 Array Query

Arrays are often present in our datasets, so it is important to query them

  1. The queryauthThere are in the arrayljcThe document
db.user.find({auth:"ljc"})
Copy the code

  1. The queryauthWe have bothljcAnd there was acssauthThe document
db.user.find({auth:{$all:["ljc","cssauth"]}})
Copy the code

  1. The queryauthThe second element in the array isljcThe document

The second element of the array is specified by auth.1

db.user.find({"auth.1":"ljc"})
Copy the code

  1. The queryauthFirst to second element in array (other fields reserved)
The db. The user. The find ({}, {auth: {$slice: [0, 2]}})Copy the code

  1. The queryauthThe last element in the array
db.user.find({},{auth:{$slice:-1}})
Copy the code

4.6 the sorting

Sort the data using the sort method, using 1 and -1 to specify whether the sort is ascending or descending

Sort the page from smallest to largest

db.user.find().sort({page:1})
Copy the code

4.7 the paging

Use the limit() method to read a specified amount of data, and skip() method to skip a specified amount of data

Syntax format:

db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)
Copy the code

The instance

Db.user.find. Limit (2). Skip (2) #3,4Copy the code

4.8 statistical

Count is used to calculate how many values fit the criteria

Count the number of pages less than 270

db.user.count({"page":{$lt:270}})
Copy the code