Mongodb basic operation


More welcome to the blog:

Mongodb version: 3.4

consult your documentation


Query all


Document query

//Query all documents with name = "Jian"

Conditional Operator

  • $LT less than
  • $GT greater than
  • $GTE is greater than or equal to
  • $LTE less than or equal to
  • $ne is not equal to
  • $all inclusive
  • $in contains
  • $Nin does not contain
//Query age less than 18


All values must be met

//You can find {age: [20,21,22]} but you can't find {age: [20,22,23]}, that is, there must be 20 and 21


This is different from $all. The query value can be found within the range given by $in.

//{age: [20,21,22]}, {age: [20,22,23]} can be found


Determine whether the key exists

Determine whether the age field exists

Processing of null values

For null value processing, it should be noted that not only records with null value of a field can be queried, but also records without a field can be found.


Records with null age and records without age field can be queried. If we need to query only the records that have the age field and the value of the age field is null, we need to cooperate with the exists operation.


Limit the number of queries


Number is the number of entries

//The number of queries is limited to 10



Key is the field to be sorted, with ascending order of 1 and descending order of – 1

//Sort by age in ascending order

Skip record


Query the records of items 10 to 20

Number of query documents


Number of pieces with age greater than 25
db.collection.find({age: {$gte: 25}}).count();

Insert document

The basic syntax of insert() is as follows:

   <document or array of documents>,
     writeConcern: <document>,
     ordered: <boolean>

Single insert


Multiple inserts


Incorrect syntax


Only age: 11 is inserted because the received inserted document is not an array





The first one is to insert two documents, the second one is to insert a document, and the third one is also a document, but because the key is repeated, only the latter value will be inserted. Age: 12

remove document

The basic syntax format of the remove () method is as follows:

     justOne: <boolean>,
     writeConcern: <document>

Parameter Description:

  • Query: (optional) the condition of the deleted document.
  • Justone: (optional) if set to true or 1, only one document will be deleted.
  • Writeconcern: (optional) the level at which the exception was thrown.

Delete data with num greater than 100{"num":{$gt:100}});

Delete all data in the new set{});

Delete data with num equal to 100{"num":100})

Update document

The update () method is used to update an existing document. The syntax format is as follows:

     upsert: <boolean>,
     multi: <boolean>,
     writeConcern: <document>

Parameter Description:

  • Query: query criteria of update, similar to the query criteria after where in SQL update query.
  • Update: the update object and some Update Operators (such as $, $Inc…) can also be understood as the object after the set in the SQL update query

Upsert: optional. This parameter means whether to insert objnew if there is no update record. True means insert. The default is false and not insert.

  • Multi: optional. Mongodb is false by default. Only the first record found will be updated. If this parameter is true, all the records found by conditions will be updated.
  • Writeconcern: optional, the level of exception thrown.

$set modifier

Used to modify the value of the key. If the key does not exist, increase the key

//Change the data of age = 10 to 15. By default, if there are multiple records of age = 10, only the first one will be updated

//Update multiple qualified values. At the same time, if the updated value does not exist, insert the updated value. Note: the value inserted here is 20, not 30

Multi and upsert can be omitted. Curly braces are not allowed here, but this is not recommended

//Update value to array

//Change to other values

$Inc modifier

It is used to increase the value of an existing key. If the key does not exist, it will be created. It can only be used for integer, long integer and floating point types.

//Press the age key of the record with name = Zhang + 10

//Set the age key of the record with name = Zhang to - 10

$unset modifier

Deleting a key is similar to deleting a field in a relational database. To distinguish between the $set modifier, set the key to null or null


$push modifier

If the array already exists, “$push” will add an element to the end of the existing array. If not, a new array will be created. Note: you must be an array to add new values

db.collection.update({"name":"zhang"},{$push:{"comments":{"email":"[email protected]","address":"beijing"}}});

//Insert another comments

$each modifier

Adding elements to an array


//Adds a single element to the list array

//Add multiple elements to the list array

$addtoset modifier

When inserting elements into the array set, if the elements exist, they will not be inserted; The method is the same as $push. The only difference is that $push does not judge duplicate values, and duplicates can also be inserted$ Addtoset can also be used together with $each. Like $push, you can insert multiple elements into the array at the same time, and if the elements exist, they will not be inserted.



$pull modifier

All elements in the matching array will be deleted. Note that only elements in the array can be matched


//Clear element 2 in list array

$pop modifier

Delete an element from the end or head of the array, $Pop: {“list”: 1}: delete an element from the end$ Pop: {“list”: – 1}: delete an element from the beginning

//Insert two elements into the array list

//Delete element from end

//Delete element from beginning

Position based array modification method
There are two ways to locate elements in an array:

1. Pass the subscript; The subscripts of the array start from 0.

2. Through the $positioning operator,

//Change the age value of the first list in the array to 20
//Method 1:

//Method 2:


Index can greatly improve the efficiency of query. If there is no index, mongodb must scan each file in the collection and select those records that meet the query conditions when reading data.

The query efficiency of scanning the whole collection is very low, especially when processing a large amount of data, the query can take tens of seconds or even minutes, which is very fatal to the performance of the website.

Index is a special data structure. Index is stored in a data set that is easy to traverse and read. Index is a structure that sorts the values of one or more columns in the database table

Ensureindex() method

Mongodb uses the ensureindex () method to create an index.

Set no as index:

1 specifies to create the index in ascending order. If you want to create the index in descending order, specify - 1.

Delete collection

Delete the test set. Note that curly braces are not required in the brackets after drop