In front of the word

This article will introduce in detail MongoDB Database on the addition, deletion and modification of documents

Inserted into the document

To insert data into  MongoDB Collection , Need to use MongoDB Of  insert() or save() Method , also insertOne() or insertMany() Method


insert() The basic syntax of the command is as follows


In the inserted document , If you don't specify _id Parameters , that MongoDB A unique... Will be assigned to this document ObjectId._id Unique for each document in the collection 12 Hexadecimal number of bytes

_id, Also known as ObjectId It's a 12 Bytes of BSON Type string . Represent... In byte order :

4 byte :UNIX Time stamp

3 byte : Said to run MongoDB Machine

2 byte : Indicates that this _id The process of

3 byte : The value generated by a counter starting with a random number

If the collection does not exist in the database , be MongoDB This collection will be created , Then insert the document into the collection

To insert multiple documents in a single query , Can be in insert() The command passes an array of documents

[ Be careful ] Use insert() When inserting multiple documents , It's easy to have problems . Best use insertMany() Method insert

have access to js grammar , Insert multiple documents


Insert documents can also be used If not specified in the document _id, that save() The method will be the same as insert() Method is the same as automatic allocation ID Value . If specified _id, It will be save() Method contains _id All data of the document .

in other words save() Methods and insert() The difference in method is ,save() Methods can be duplicated or modified , and insert() Method can not


Use db.collection.insertOne() Method to insert a single document into a collection


Use db.collection.insertMany() Method to insert multiple documents into a collection

Query the document


From you to MongoDB Set query data , Need to use MongoDB Of find() Method , By default, the first... In the result is returned 20 Documents , Input "it" Show the next 20 Documents .

find() The basic syntax of the command is as follows :


find() Method will display all documents in an unstructured way

You can limit the query conditions

Can pass find To specify the returned key , The value is 1 or true Indicates that the key is displayed , The value is 0 or false Indicates that the key is not displayed

find() Under the method count() Method to display the number of eligible documents


findOne() Method returns only one document , This is the first document to be added

【 Comparison operator 】

 Less than {<key>:{$lt:<value>}}
Less than or equal to {<key>:{$lte:<value>}}
Greater than {<key>:{$gt:<value>}}
Greater than or equal to {<key>:{$gte:<value>}}
It's not equal to {<key>:{$ne:<value>}}
be equal to {<key>:{$eq:<value>}}

obtain x Less than 2 Value

obtain x Greater than or equal to 2 Value

obtain x It's not equal to 2 Value

【 Logical operators 】

You can use logical operators $and、$or To express and 、 or

{ $and: [ { <expression1> }, { <expression2> } , ... , { <expressionN> } ] }
{ $nor: [ { <expression1> }, { <expression2> }, ... { <expressionN> } ] }

【 Regular expressions 】

Document queries can use regular expressions , But only string type data is supported


$where Operators are powerful and flexible , It can use any JavaScript As part of the query , contain JavaScript The string of the expression or JavaScript function

Use string

Using functions

Limit and skip


If you need to MongoDB Read a specified number of data records , have access to MongoDB Of Limit Method ,limit() Method accepts a numeric parameter , This parameter specifies from MongoDB Number of records read in

By default, the first... In the result is returned 20 Documents , Input "it" Show the next 20 Documents

If not specified limit() The parameters in the method display all the data in the collection



have access to skip() Method to skip a specified amount of data ,skip Method also accepts a numeric parameter as the number of records to skip




stay MongoDB Use in sort() Method to sort the data ,sort() Method can be used to specify the sorting field by parameter , And use 1 and -1 To specify how to sort , among 1 Arrange... In ascending order , and -1 It's for descending order


Update the document

MongoDB Use update() or save() Method to update the document in the collection


update() Method to update an existing document . The syntax is as follows :

db.collection.update(<query>,<update>,{upsert:<boolean>, multi: <boolean>,writeConcern:<document>})
query : update Query criteria for , similar sql update In the query where hinder 
update : update Object and some updated operators ( Such as $,$inc...) etc. , It can also be understood as sql update In the query set hinder
upsert : Optional , This parameter means , If it doesn't exist update The record of , Whether insert objNew,true Insert for , The default is false, Do not insert
multi : Optional ,mongodb The default is false, Update only the first record found , If this parameter is zero true, According to the conditions to find out all the records updated
writeConcern : Optional , The level at which an exception is thrown

[ Be careful ] After testing ,upsert Parameter cannot be set to true perhaps false, You can insert new fields

mongodb Only the first record found is updated by default , take x:1, Updated to x:10

Pay special attention to , If not used $set, Replace the content of the document with x:10

Update all records , take x:10, Updated to x:1

mongodb Only the first record found by update is added by default , take x:1 The record of , add to z:1

Will find the x:2 All the records of , add to z:2


save() Method to insert or update a document , If the document in the parameter _id And what exists in the set _id All different , The insert ; If the same , Update

Delete the document

MongoDB remove() Function is used to remove data from a collection


By default ,mongodb Delete all eligible documents

db.collection.remove(<query>,{justOne: <boolean>, writeConcern: <document>})
query : Conditions for deleted documents .
justOne : ( Optional ) If it is set to true or 1, Only one document is deleted .
writeConcern :( Optional ) The level at which an exception is thrown .

Delete only the first document that meets the criteria

Delete all eligible documents

MongoDB More articles on database document manipulation

  1. MongoDB introduction --- The addition, deletion and modification of document operation

    Two previous articles , Have shared about MongoDB There are also various operations of the database , Next, we will talk about the most important , That's the operation of data , It's called document manipulation here . Don't talk much , Let's look at the text .     First, let's look at its data structure : ...

  2. MongoDB ( 8、 ... and ) MongoDB The document operation

    One . MongoDB Inserted into the document insert() Method To insert data into MongoDB aggregate , Need to use MongoDB Of  insert()  or  save()  Method . grammar insert()  The base of command ...

  3. MongoDB Documents 、 aggregate 、 database ( Two )

    In order to understand MongoDB The noun , You can compare it with a relational database : One . file summary The document is MongoDB Core concept of , It's the basic unit of data , Very similar to rows in a relational database . stay MongoDB in , The document is represented as one of the key value pairs ...

  4. mongodb install , Library operation , Set operations ( surface ), The document operation ( Record )

    install 1. Download address 2. If not ...

  5. MongoDB series --- Collections and document operations 03

    MongoDB-——Collection Syllabus : 1. Set operations 2. The document operation Knowledge review : In the last article we talked about how to deal with MongoDB The authority and users of the daily basic operation , To achieve our basic security of the database . One ...

  6. mongoDB The document operation 【 Additions and deletions 】

    MongoDB  Inserted into the document Document data structure and JSON Is essentially the same . All data stored in the collection is BSON Format . BSON Is a kind json A storage format in binary form , abbreviation Binary JSON. Inserted into the document Mo ...

  7. mongodb Query the document

    When it comes to queries , We usually think of the query of relational database , such as :order by( Sort ).limit( Pagination ). Range queries ( Greater than a certain value , Less than a certain value ..,in Inquire about ,on Inquire about ,like Queries wait a lot ), Again mongodb ...

  8. Chapter one : One day learn MongoDB Database Python operation

    This article is just about learning to use , from : There is a new one in it Python Add, delete, modify and check the code What is? MongoD ...

  9. 【C# Source code attached 】 Database document generation tool supports (Excel+Html)

    [2015] A lot of times , When we generate database documents , Using certain tools , But the effect is not ideal , It's not that the content is not detailed , It's just that the performance effect is average . A lot or word.html Of . It's awkward to look at . I am used to Excel, So in your spare time , It's simple ...

Random recommendation

  1. Analysis of large .NET ERP System Thirteen interface design patterns

    ripe ERP The interface of the system should be copied from the template , The interface of various functions has rules to follow . Software interface design pattern or artistic creation , I agree with the former , It's easy for customers to draw inferences from one instance with a patterned interface , Lower the learning threshold . In addition to a small part of the functional interface design features ...

  2. sqlserver Get table name , Field name

    One . Get the basic information of the table SELECT [TableName] = [Tables].name , [TableOwner] = [Schemas].name , [TableCreateDate] = ...

  3. UML series 02 And UML Class diagram (2)

    UML Several relations of class diagram stay UML In class diagram , Relationships can be divided into 4 Kind of : generalization , Realization , relation and rely on .1. generalization -- Express " The inheritance relationship between classes ".2. Realization -- Express " Classes and interfaces ...

  4. DAT How to open a file

    DAT The main types of documents are " data " file . Can be anything , example : written words , graphics , Video or general binary data , It doesn't have a unified detailed structure . So you can't understand that it also corresponds to an application to open it . For example, you see a ...

  5. BZOJ 1093: [ZJOI2007] The largest semi connected subgraph ( tarjan + dp )

    WA Many times. ... First tarjan Shrinkage point , Then the meaning of the question is to ask for DAG One of the longest chains on . dp(u) = max{dp(v)} + totu, edge(u,v) There is . totu yes scc(u) The number of knots . In fact ...

  6. SHA Algorithm

    Security Hash function (SHA) Is the most widely used Hash function . Because of other widely used Hash Functions are found to have security risks , from 2005 So far this year ,SHA Maybe it's the only one left Hash Algorithm standard . SHA The history of SHA By American standards and Technology ...

  7. It's over ten thousand a month Java Advanced learning materials , Rare dry goods , It's a pity not to download !

    Do you miss me Whether you want me or not I miss you very much Through yesterday I kept All kinds of good words Final It's coming Java Of course Java Collect learning materials It contains videos + Information + Source code My cousin also has a wish I hope your monthly salary will be over ten thousand ...

  8. program_options

    [program_options] The program_options library allows program developers to obtain program options, t ...

  9. HDU 3848 CC On The Tree( Tree form dp) The question : Find the shortest distance between two leaf nodes on a tree . Ideas : Two leaf nodes must pass through non leaf nodes , Unless there are only two ...

  10. node api And :process - process

    process An object is a global variable , It provides the current Node.js Information about the process , And control the current Node.js process . Because it's a global variable , So there's no need to use require().