MongoDB insert document
In this section we show you how to insert data into a MongoDB collection.
The data structure of the document is basically the same as JSON.
All data stored in the collection is in BSON format.
BSON is a jSON-like storage format, short for Binary JSON.
Inserted into the document
MongoDB inserts documents into the collection using insert() or save() methods with the following syntax:
db.COLLECTION_NAME.insert(document)
Copy the code
The instance
The following documents can be stored in the COL collection of MongoDB’s Runoob database:
>db.col.insert({title: 'MongoDB ', description: 'MongoDB is a Nosql database ', by: 'Nosql ', url: 'http://www.runoob.com', tags: ['mongodb', 'database', 'NoSQL'], likes: 100 })Copy the code
Col is our collection name in the above example, and if the collection is not in the database, MongoDB automatically creates the collection and inserts the document.
View the inserted document:
> db.col.find() {"_id" : ObjectId("56064886ade2f21f36b03134"), "title" : "MongoDB guide ", "description" : "MongoDB is a Nosql database ", "by" : "Novice tutorial "," URL ": "http://www.runoob.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 } >Copy the code
We can also define data as a variable, as follows:
> document=({title: 'MongoDB ', description: 'MongoDB is a Nosql database ', by: 'Nosql ', url: 'http://www.runoob.com', tags: ['mongodb', 'database', 'NoSQL'], likes: 100 });Copy the code
The following information is displayed:
{"title" : "MongoDB ", "description" : "MongoDB is a Nosql database ", "by" : "Nosql ", "url" : "http://www.runoob.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 }Copy the code
Perform the insert operation:
> db.col.insert(document)
WriteResult({ "nInserted" : 1 })
>
Copy the code
You can also insert documents using db.col.save(document). The save() method is similar to the INSERT () method if the _ID field is not specified. If the _id field is specified, the _id data is updated.
MongoDB delete collection
MongoDB Update documentation
Write notes
-
Two little
272***[email protected]
Refer to the address
After version 3.2, the following syntax is available for inserting documents:
- Db.collection.insertone (): Inserts a piece of document data into the specified collection
- Db.collection.insertmany (): Inserts multiple document data into the specified collection
Var document = db.collection.insertOne({"a": 3}) > document {" indispensable ": true, "insertedId" : ObjectId("571a218011a82a1d94c02333")} # Insert multiple data > var res = db.collection.insertmany ([{"b": 3}, {'c': 4}]) > res { "acknowledged" : true, "insertedIds" : [ ObjectId("571a22a911a82a1d94c02337"), ObjectId("571a22a911a82a1d94c02338") ] }Copy the code
Two little
Two little
272***[email protected]
Refer to the address
Two years ago (2017-07-12)
-
Tffans
897***[email protected]
Insert multiple pieces of data at once
1. Create an array
2. Put the data in an array
3, an insert into the collection
var arr = []; for(var i=1 ; i<=20000 ; i++){ arr.push({num:i}); } db.numbers.insert(arr); Copy the code
MongoDB Update documentation
MongoDB uses the update() and save() methods to update the documents in the collection. Let’s take a closer look at the two functions and their differences.
The update () method
The update() method is used to update an existing document. The syntax is as follows:
db.collection.update(
<query>.<update>,
{
upsert: <boolean>,
multi: <boolean>,
writeConcern: <document>})Copy the code
Parameter Description:
- Query: The query condition is similar to where in the SQL update query.
- Update: Update objects and some update operators (such as $,$inc…) SQL update set ()
- Upsert: Optional, this parameter means whether to insert objNew if no update record exists. True is insert, default is false, no insert.
- Multi: Optional. By default, mongodb updates only the first found record. If this parameter is true, mongodb updates all found records.
- WriteConcern: Optional, level of exception thrown.
The instance
We insert the following data into the col collection:
>db.col.insert({title: 'MongoDB ', description: 'MongoDB is a Nosql database ', by: 'Nosql ', url: 'http://www.runoob.com', tags: ['mongodb', 'database', 'NoSQL'], likes: 100 })Copy the code
Next we update the title with the update() method:
> db. Col. Update ({' title ':' directing a tutorial '}, {$set: {" title ":" mongo "}}) WriteResult ({" nMatched ": 1," nUpserted ": Db.col.find (). Pretty () {"_id" : ObjectId(" 56064F89ade2f21f36b03136 "), "title" : "MongoDB", "description" : "MongoDB is a Nosql database ", "by" : "novice tutorial ", "url" : "http://www.runoob.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 } >Copy the code
You can see that the title has been updated from “MongoDB Tutorial “to “MongoDB”.
The above statement will only modify the first discovered document. If you want to modify multiple documents, set the multi parameter to true.
> db. Col. Update ({' title ':' directing a tutorial '}, {$set: {" title ":" mongo "}}, {multi: true})Copy the code
Save () method
The save() method replaces the existing document with the incoming document. The syntax is as follows:
db.collection.save(
<document>,
{
writeConcern: <document>})Copy the code
Parameter Description:
- Document: Document data.
- WriteConcern: Optional, level of exception thrown.
The instance
In the following example, we replace the document whose id is 56064F89ADE2F21F36B03136:
>db.col.save({ "_id" : ObjectId("56064f89ade2f21f36b03136"), "title" : "MongoDB", "description" : "MongoDB is a Nosql database ", "by" : "Runoob", "URL" : "http://www.runoob.com", "tags" : ["MongoDB ", "Nosql"], "likes" : 110})Copy the code
After the replacement is successful, you can use the find() command to view the data after the replacement
>db.col.find().pretty() { "_id" : ObjectId("56064f89ade2f21f36b03136"), "title" : "MongoDB", "description" : "MongoDB is a Nosql database ", "by" : "Runoob", "URL" : "http://www.runoob.com", "tags" : ["MongoDB ", "Nosql"], "likes" : 110} >Copy the code
More instances
Update only the first record:
db.col.update( { “count” : { $gt : 1 } } , { $set : { “test2” : “OK”} } );
All Updates:
db.col.update( { “count” : { $gt : 3 } } , { $set : { “test2” : “OK”} },false,true );
Add only the first:
db.col.update( { “count” : { $gt : 4 } } , { $set : { “test5” : “OK”} },true,false );
Add all:
db.col.update( { “count” : { $gt : 5 } } , { $set : { “test5” : “OK”} },true,true );
All Updates:
db.col.update( { “count” : { $gt : 15 } } , { $inc : { “count” : 1} },false,true );
Update only the first record:
db.col.update( { “count” : { $gt : 10 } } , { $inc : { “count” : 1} },false,false );
MongoDB delete document
In the previous chapters we learned how to add and update data to collections in MongoDB. In this section we will continue to learn about MongoDB collection deletion.
The MongoDB remove() function is used to remove data from the collection.
MongoDB data can be updated using the update() function. It is a good practice to execute find() before executing remove() to determine if the condition is correct.
grammar
The basic syntax of the remove() method looks like this:
db.collection.remove(
<query>.<justOne>
)
Copy the code
If you have MongoDB after version 2.6, the syntax is as follows:
db.collection.remove(
<query>,
{
justOne: <boolean>,
writeConcern: <document>})Copy the code
Parameter Description:
- Query :(optional) conditions for the document to be deleted.
- JustOne: (Optional) If this parameter is set to true or 1, only one document is deleted. If this parameter is not set, or the default value false is used, all documents matching the criteria are deleted.
- WriteConcern :(optional) level of an exception thrown.
The instance
We insert twice in the following documents:
>db.col.insert({title: 'MongoDB ', description: 'MongoDB is a Nosql database ', by: 'Nosql ', url: 'http://www.runoob.com', tags: ['mongodb', 'database', 'NoSQL'], likes: 100 })Copy the code
Use find() to query data:
> db.col.find() {"_id" : ObjectId("56066169ade2f21f36b03137"), "title" : "MongoDB guide ", "description" : "MongoDB is a Nosql database ", "by" : "Novice tutorial "," URL ": "http://www.runoob.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 } { "_id" : ObjectId("5606616dade2f21f36b03138"), "title" : "MongoDB ", "description" : "MongoDB is a Nosql database ", "by" : "Nosql ", "url" : "http://www.runoob.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 }Copy the code
Next we remove the document with the title ‘MongoDB Tutorial ‘:
>db.col.remove({'title':'MongoDB tutorial '}) WriteResult({"nRemoved" : 2}) # remove two data >db.col.find()... # No dataCopy the code
If you want to delete only the first record found, set justOne to 1, as shown below:
>db.COLLECTION_NAME.remove(DELETION_CRITERIA,1)
Copy the code
If you want to delete all data, use the following method (similar to the truncate command in regular SQL) :
>db.col.remove({})
>db.col.find()
>
Copy the code
MongoDB Update documentation
MongoDB query document
Write notes
-
Three Kingdoms TV station
tre***[email protected]
The remove() method is obsolete, and the deleteOne() and deleteMany() methods are now officially recommended.
If delete all documents under collection:
db.inventory.deleteMany({}) Copy the code
Delete all documents where status = A:
db.inventory.deleteMany({ status : "A" }) Copy the code
Delete a document where status equals D:
db.inventory.deleteOne( { status: "D" } ) Copy the code
Three Kingdoms TV station
Three Kingdoms TV station
tre***[email protected]
Two years ago (2017-09-22)
-
sairre
jsa***[email protected]
The remove() method doesn’t really free up space.
The DB.RepairDatabase () needs to continue to reclaim disk space.
RepairDatabase () or > db.runCommand({repairDatabase: 1})Copy the code
MongoDB query document
MongoDB queries documents using the find() method.
The find() method displays all documents in an unstructured manner.
grammar
The syntax format of MongoDB query data is as follows:
db.collection.find(query, projection)
Copy the code
- Query: Optional. Use the query operator to specify the query conditions
- Projection: Optional, using the projection operator to specify the key to return. Query returns all key values in the document, simply omit this parameter (the default is omitted).
If you need to read data in a readable way, you can use the pretty() method, which has the following syntax:
>db.col.find().pretty()
Copy the code
The pretty() method displays all documents in a formatted manner.
The instance
In the following example, we query data from col:
> db.col.find().pretty() {"_id" : ObjectId("56063f17ade2f21f36b03133"), "title" : "MongoDB guide ", "description" : "MongoDB is a Nosql database ", "by" : "Novice tutorial "," URL ": "http://www.runoob.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 }Copy the code
In addition to the find() method, there is a findOne() method that returns only one document.
MongoDB compared to the RDBMS Where statement
If you are familiar with regular SQL data, you can use the following table to better understand MongoDB’s conditional query:
operation | format | sample | Similar statements in an RDBMS |
---|---|---|---|
Is equal to the | {<key>:<value> } |
Db.col.find ({"by":" 教程"}).pretty() |
Where by = ' ' |
Less than | {<key>:{$lt:<value>}} |
db.col.find({"likes":{$lt:50}}).pretty() |
where likes < 50 |
Less than or equal to | {<key>:{$lte:<value>}} |
db.col.find({"likes":{$lte:50}}).pretty() |
where likes <= 50 |
Is greater than | {<key>:{$gt:<value>}} |
db.col.find({"likes":{$gt:50}}).pretty() |
where likes > 50 |
Greater than or equal to | {<key>:{$gte:<value>}} |
db.col.find({"likes":{$gte:50}}).pretty() |
where likes >= 50 |
Is not equal to | {<key>:{$ne:<value>}} |
db.col.find({"likes":{$ne:50}}).pretty() |
where likes ! = 50 |
Directing the AND conditions
MongoDB’s find() method can pass in multiple keys, each separated by a comma, the AND condition of regular SQL.
The syntax is as follows:
>db.col.find({key1:value1, key2:value2}).pretty()
Copy the code
The instance
The following example uses the BY and title keys to query data for the MongoDB tutorial in the Rookie tutorial
> db.col.find({"by":" ObjectId ", "title":"MongoDB "}). Pretty () {" _id" : ObjectId("56063f17ade2f21f36b03133"), "title": "MongoDB ", "description" : "MongoDB is a Nosql database ", "by" : "Nosql ", "url" : "http://www.runoob.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 }Copy the code
WHERE by=’ MongoDB ‘AND title=’MongoDB’
Directing the OR conditions
The MongoDB OR conditional statement uses the keyword $OR, and the syntax format is as follows:
>db.col.find(
{
$or: [
{key1: value1}, {key2:value2}
]
}
).pretty()
Copy the code
The instance
In the following example, we demonstrate a query for a document whose key by value is a rookie tutorial or whose key title value is a MongoDB tutorial.
> db. Col. Find ({$or: [{" by ":" novice tutorial "}, {" title ":" mongo tutorial "}]}). Pretty () {" _id ": ObjectId(" 56063f17ade2f21f36B03133 "), "title" : "MongoDB guide ", "description" : "MongoDB is a Nosql database ", "by" : "Rookie tutorial", "url" : "http://www.runoob.com", "tags" : [" mongo ", "database", "no"], "likes" : 100} >Copy the code
AND AND OR are used together
Example: ‘where likes>50 AND (by = ‘OR title = ‘MongoDB ‘)’
> db. Col. Find ({" likes ": {$gt: 50}, $or: [{" by" : "novice tutorial"}, {" title ":" mongo tutorial "}]}). Pretty () {" _id ": ObjectId(" 56063f17ade2f21f36B03133 "), "title" : "MongoDB guide ", "description" : "MongoDB is a Nosql database ", "by" : "Rookie tutorial", "url" : "http://www.runoob.com", "tags" : [" mongo ", "database", "no"], "likes" : 100}Copy the code
MongoDB delete document
MongoDB conditional operator
Write notes
-
DisLido
Add the use of the projection parameter
db.collection.find(query, projection) Copy the code
If no projection is specified, all keys are returned by default. The projection format is as follows, and there are two modes
Db.collection. find(query, {title: 1, by: 1}) // Inclusion mode specifies the keys to return and does not return other keys db.collection.find(query, {title: 0, by: 1}) 0}) // Exclusion mode specifies non-return keys and returns other keysCopy the code
The _id key is returned by default. You must specify _id:0 to hide it
The two modes should not be mixed (because it is impossible to infer whether the other key should be returned)
Db.collection. find(query, {title: 1, by: 0}) // ErrorCopy the code
Only all 1s or zeros are allowed, except in inclusion mode where the _id can be specified as 0
Db.collection. find(query, {_id:0, title: 1, by: 1}) // CorrectCopy the code
-
pengll
If you do not want to specify query, use {} instead, but you need to specify the projection parameter:
querydb.collection.find({}, {title: 1}) Copy the code
-
Parting Hook
If qty is greater than 50 and less than 80, you cannot write this:
db.posts.find( { qty: { $gt: 50 }, qty: { $lt: 80 } } ) Copy the code
It should go like this:
db.posts.find( { qty: { $gt: 50 ,$lt: 80}} ) Copy the code
MongoDB conditional operator
describe
The conditional operator is used to compare two expressions and retrieve data from the mongoDB collection.
In this section, we discuss how to use conditional operators in MongoDB.
Conditional operators in MongoDB include:
- > > > – $gt
- (<) less than – $lt
- (>=) greater than or equal to – $gte
- (<=) Is less than or equal to – $LTE
The database we use is called “Runoob” and our collection is called “COL”. Here is the data we inserted.
For testing purposes, we can use the following command to clear the data from the collection “col” :
db.col.remove({})
Copy the code
Insert the following data
>db.col.insert({title: 'PHP tutorial ', description: 'PHP is a powerful server-side scripting language for creating dynamic interactive sites. ', by: 'rookie tutorial, url:' http://www.runoob.com ', tags: [' PHP '], "likes" : 200})Copy the code
>db.col.insert({title: 'Java tutorial ', description: 'Java is a high-level programming language introduced by Sun Microsystems in May 1995. ', by: 'rookie tutorial, url:' http://www.runoob.com ', tags: [' Java '], "likes" : 150})Copy the code
>db.col.insert({title: 'MongoDB ', description: 'MongoDB is a Nosql database ', by: 'Nosql ', url: 'http://www.runoob.com', tags: ['mongodb'], likes: 100 })Copy the code
Use the find() command to view the data:
> db.col.find() {"_id" : ObjectId("56066542ade2f21f36b0313a"), "title" : "PHP guide ", "description" : PHP is a powerful server-side scripting language for creating dynamic, interactive sites. Rookie tutorial, "by" : ""," url ":" http://www.runoob.com ", "tags" : [" PHP "], "likes" : 200} {" _id ": ObjectId(" 56066549ade2f21F36B0313b "), "title" : "Java tutorial ", "description" : Java is a high-level programming language introduced by Sun Microsystems in May 1995. Rookie tutorial, "by" : ""," url ":" http://www.runoob.com ", "tags" : [" Java "], "likes" : 150} {" _id ": ObjectId(" 5606654FAde2f21f36B0313c "), "title" : "MongoDB tutorials ", "description" : "MongoDB is a Nosql database ", "by" : "Rookie tutorial", "url" : "http://www.runoob.com", "tags" : [" mongo "], "likes" : 100}Copy the code
MongoDB (>) > operator – $gt
If you want to get data with “likes” greater than 100 in the “col” set, you can use the following command:
db.col.find({likes : {$gt : 100}})
Copy the code
Similar to SQL statements:
Select * from col where likes > 100;
Copy the code
Output result:
> db.col.find({likes : {$gt : 100}}) { "_id" : ObjectId("56066542ade2f21f36b0313a"), "title" : "PHP Tutorial ", "Description" : "PHP is a powerful server-side scripting language for creating dynamic interactive sites." Rookie tutorial, "by" : ""," url ":" http://www.runoob.com ", "tags" : [" PHP "], "likes" : 200} {" _id ": ObjectId(" 56066549ade2f21F36B0313b "), "title" : "Java tutorial ", "description" : Java is a high-level programming language introduced by Sun Microsystems in May 1995. Rookie tutorial, "by" : ""," url ":" http://www.runoob.com ", "tags" : [" Java "], "likes" : 150} >Copy the code
MongoDB (>=) greater than or equal to operator – $gte
If you want to get data with “likes” greater than or equal to 100 in the “col” set, you can use the following command:
db.col.find({likes : {$gte : 100}})
Copy the code
Similar to SQL statements:
Select * from col where likes >=100;
Copy the code
Output result:
> db.col.find({likes : {$gte : 100}}) { "_id" : ObjectId("56066542ade2f21f36b0313a"), "title" : "PHP Tutorial ", "Description" : "PHP is a powerful server-side scripting language for creating dynamic interactive sites." Rookie tutorial, "by" : ""," url ":" http://www.runoob.com ", "tags" : [" PHP "], "likes" : 200} {" _id ": ObjectId(" 56066549ade2f21F36B0313b "), "title" : "Java tutorial ", "description" : Java is a high-level programming language introduced by Sun Microsystems in May 1995. Rookie tutorial, "by" : ""," url ":" http://www.runoob.com ", "tags" : [" Java "], "likes" : 150} {" _id ": ObjectId(" 5606654FAde2f21f36B0313c "), "title" : "MongoDB tutorials ", "description" : "MongoDB is a Nosql database ", "by" : "Rookie tutorial", "url" : "http://www.runoob.com", "tags" : [" mongo "], "likes" : 100} >Copy the code
MongoDB (<) is less than the operator – $lt
If you want to get data with “likes” less than 150 in the “col” collection, you can use the following command:
db.col.find({likes : {$lt : 150}})
Copy the code
Similar to SQL statements:
Select * from col where likes < 150;
Copy the code
Output result:
> db.col.find({likes : {$lt : 150}}) { "_id" : ObjectId("5606654fade2f21f36b0313c"), "title" : "MongoDB ", "description" : "MongoDB is a Nosql database ", "by" : "Nosql ", "url" : "http://www.runoob.com", "tags" : [ "mongodb" ], "likes" : 100 }Copy the code
MongoDB (<=) less than or equal to operator – $lte
If you want to get data with “likes” less than or equal to 150 in the “col” collection, you can use the following command:
db.col.find({likes : {$lte : 150}})
Copy the code
Similar to SQL statements:
Select * from col where likes <= 150;
Copy the code
Output result:
> db.col.find({likes : {$lte : 150}}) { "_id" : ObjectId("56066549ade2f21f36b0313b"), "title" : "Java Tutorial ", "Description" : "Java is a high-level programming language introduced by Sun Microsystems in May 1995." Rookie tutorial, "by" : ""," url ":" http://www.runoob.com ", "tags" : [" Java "], "likes" : 150} {" _id ": ObjectId(" 5606654FAde2f21f36B0313c "), "title" : "MongoDB tutorials ", "description" : "MongoDB is a Nosql database ", "by" : "Rookie tutorial", "url" : "http://www.runoob.com", "tags" : [" mongo "], "likes" : 100}Copy the code
MongoDB uses (<) and (>) queries – $lt and $gt
If you want to get “likes” greater than 100 and less than 200 from the “col” set, you can use the following command:
db.col.find({likes : {$lt :200, $gt : 100}})
Copy the code
Similar to SQL statements:
Select * from col where likes>100 AND likes<200;
Copy the code
Output result:
> db.col.find({likes : {$lt :200, $gt : 100}}) { "_id" : ObjectId("56066549ade2f21f36b0313b"), "title" : "Java Tutorial ", "Description" : "Java is a high-level programming language introduced by Sun Microsystems in May 1995." Rookie tutorial, "by" : ""," url ":" http://www.runoob.com ", "tags" : [" Java "], "likes" : 150} >Copy the code
MongoDB query document
MongoDB $type operator
Write notes
-
Mrt.L
903***[email protected]
Some shorthand notes:
$gt -------- greater than > $gte --------- gt equal >= $lt -------- less than < $lte --------- lt equal <= $ne ----------- not equal ! = $eq -------- equal =Copy the code
Mrt.L
Mrt.L
903***[email protected]
Two years ago (2017-07-12)
-
Original dream
660***[email protected]
Fuzzy query
Select * from documents where title contains “teach”;
Db. Col. Find ({title: / teach /})Copy the code
Select * from documents where title begins with “teach”;
Db. Col. Find ({title: ^ teach /})Copy the code
Select * from titl E where titl e ends in “teach” :
Db. Col. Find ({title: / teach $/})Copy the code
MongoDB $type operator
describe
In this section, we continue our discussion of the conditional operator $type in MongoDB.
The $type operator retrieves the matching data type in the collection based on the BSON type and returns the result.
The following table lists the types that can be used in MongoDB:
type | digital | note |
---|---|---|
Double | 1 | |
String | 2 | |
Object | 3 | |
Array | 4 | |
Binary data | 5 | |
Undefined | 6 | Has been abandoned. |
Object id | 7 | |
Boolean | 8 | |
Date | 9 | |
Null | 10 | |
Regular Expression | 11 | |
JavaScript | 13 | |
Symbol | 14 | |
JavaScript (with scope) | 15 | |
32-bit integer | 16 | |
Timestamp | 17 | |
64-bit integer | 18 | |
Min key | 255 | Query with -1. |
Max key | 127 |
The database we use is called “Runoob” and our collection is called “COL”. Here is the data we inserted.
Simple set “col” :
>db.col.insert({title: 'PHP tutorial ', description: 'PHP is a powerful server-side scripting language for creating dynamic interactive sites. ', by: 'rookie tutorial, url:' http://www.runoob.com ', tags: [' PHP '], "likes" : 200})Copy the code
>db.col.insert({title: 'Java tutorial ', description: 'Java is a high-level programming language introduced by Sun Microsystems in May 1995. ', by: 'rookie tutorial, url:' http://www.runoob.com ', tags: [' Java '], "likes" : 150})Copy the code
>db.col.insert({title: 'MongoDB ', description: 'MongoDB is a Nosql database ', by: 'Nosql ', url: 'http://www.runoob.com', tags: ['mongodb'], likes: 100 })Copy the code
Use the find() command to view the data:
> db.col.find() {"_id" : ObjectId("56066542ade2f21f36b0313a"), "title" : "PHP guide ", "description" : PHP is a powerful server-side scripting language for creating dynamic, interactive sites. Rookie tutorial, "by" : ""," url ":" http://www.runoob.com ", "tags" : [" PHP "], "likes" : 200} {" _id ": ObjectId(" 56066549ade2f21F36B0313b "), "title" : "Java tutorial ", "description" : Java is a high-level programming language introduced by Sun Microsystems in May 1995. Rookie tutorial, "by" : ""," url ":" http://www.runoob.com ", "tags" : [" Java "], "likes" : 150} {" _id ": ObjectId(" 5606654FAde2f21f36B0313c "), "title" : "MongoDB tutorials ", "description" : "MongoDB is a Nosql database ", "by" : "Rookie tutorial", "url" : "http://www.runoob.com", "tags" : [" mongo "], "likes" : 100}Copy the code
The MongoDB operator – $type instance
If you want to retrieve data from the “col” collection with title String, you can use the following command:
Db. Col. Find ({" title ": {$type: 2}}) or the col. Find ({" title" : {$type: 'string'}})Copy the code
The output is:
{"_id" : ObjectId("56066542ade2f21f36b0313a"), "title" : "PHP tutorial ", "description" : "PHP is a powerful server-side scripting language for creating dynamic, interactive sites." Rookie tutorial, "by" : ""," url ":" http://www.runoob.com ", "tags" : [" PHP "], "likes" : 200} {" _id ": ObjectId(" 56066549ade2f21F36B0313b "), "title" : "Java tutorial ", "description" : Java is a high-level programming language introduced by Sun Microsystems in May 1995. Rookie tutorial, "by" : ""," url ":" http://www.runoob.com ", "tags" : [" Java "], "likes" : 150} {" _id ": ObjectId(" 5606654FAde2f21f36B0313c "), "title" : "MongoDB tutorials ", "description" : "MongoDB is a Nosql database ", "by" : "Rookie tutorial", "url" : "http://www.runoob.com", "tags" : [" mongo "], "likes" : 100}Copy the code
MongoDB Limit and Skip methods
Directing a Limit () method
If you need to read a specified number of data records in MongoDB, you can use MongoDB’s Limit method, which takes a numeric argument specifying the number of records to read from MongoDB.
grammar
The basic syntax for the limit() method is as follows:
>db.COLLECTION_NAME.find().limit(NUMBER)
Copy the code
The instance
The data in the col collection is as follows:
{"_id" : ObjectId("56066542ade2f21f36b0313a"), "title" : "PHP tutorial ", "description" : "PHP is a powerful server-side scripting language for creating dynamic, interactive sites." Rookie tutorial, "by" : ""," url ":" http://www.runoob.com ", "tags" : [" PHP "], "likes" : 200} {" _id ": ObjectId(" 56066549ade2f21F36B0313b "), "title" : "Java tutorial ", "description" : Java is a high-level programming language introduced by Sun Microsystems in May 1995. Rookie tutorial, "by" : ""," url ":" http://www.runoob.com ", "tags" : [" Java "], "likes" : 150} {" _id ": ObjectId(" 5606654FAde2f21f36B0313c "), "title" : "MongoDB tutorials ", "description" : "MongoDB is a Nosql database ", "by" : "Rookie tutorial", "url" : "http://www.runoob.com", "tags" : [" mongo "], "likes" : 100}Copy the code
The following example shows two records in a query document:
> db. Col. Find ({}, {" title ": 1, _id: 0}). The limit (2) {" title" : "PHP tutorial"} {" title ":" Java tutorial} ">Copy the code
Note: Display all data in the collection if you do not specify parameters in the limit() method.
Directing the Skip () method
In addition to reading a specified amount of data using the limit() method, we can skip a specified amount of data using the skip() method, which also takes a numeric parameter as the number of records to skip.
grammar
Skip () script syntax format is as follows:
>db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)
Copy the code
The instance
The following example shows only the second document data
> db. Col. Find ({}, {" title ": 1, _id: 0}). Limit (1). Skip (1) {" title" : "Java tutorial}" >Copy the code
Note: The default parameter of the skip() method is 0.
MongoDB $type operator
Directing a sort
Write notes
-
Heaven people _2008
yan***[email protected]
db.col.find({},{"title":1,_id:0}).limit(2) Copy the code
Supplementary notes:
- The first {} puts a WHERE condition, which is null to return all documents in the collection.
- The second {} specifies which columns to show and which not to show (0 means not to show and 1 means to show).
Heaven people _2008
Heaven people _2008
yan***[email protected]
Two years ago (2017-04-17)
-
joyran
xin***[email protected]
Wanting to read the next 100 records from 10 is equivalent to limit (10,100) in SQL.
> db.COLLECTION_NAME.find().skip(10).limit(100) Copy the code
The above instance skips the first 10 entries in the collection and returns 100 entries.
The combination of SKIP and limit enables paging.
joyran
joyran
xin***[email protected]
Two years ago (2017-04-20)
-
dragon
lib***[email protected]
Refer to the address
The skip and limit methods are only suitable for small data pages, which can be very inefficient for millions of levels because the skip method is used to count data in rows. Use where_limit instead
After looking at some of the materials, I found that all the materials said this:
Skip should not be used to query easily, otherwise a large amount of data will lead to a sharp decline in performance. This is because Skip is counted one by one, and more skips will naturally slow down.
So Skip should be avoided. How can it be avoided? First, we’ll review the latter timestamp paging scheme for SQL paging. This takes advantage of the ordered nature of the fields and uses queries to fetch data without having to do a lot of counting. In other words, if you can attach conditions like this to the query it will be more efficient. Is that true? Let’s verify:
Query 100001 (Amount = 2399927);
b.test.sort({"amount":1}).skip(100000).limit(10) //183ms db.test.find({amount:{$gt:2399927}}).sort({"amount":1}).limit(10) //53ms Copy the code
The results have been attached to the comments, and it is clear that the latter is a third of the performance of the former, which is a significant difference. It also confirms the theory of Skip’s poor efficiency.
You can contact [email protected] to learn from each other.
dragon
dragon
lib***[email protected]
Refer to the address
Two years ago (2017-09-14)
-
niuyongjie
niu***[email protected]
Limit (n) is used to specify the number of entries to display, while skip(n) is used to skip from the first entry in the qualifying record, and the two functions can be used interchangeably.
For example: find({},{age:1,_id:0}).limit(2).skip(1). That’s not easy to understand.
Find ({},{age:1,_id:0}).skip(1).limit(2)
niuyongjie
niuyongjie
niu***[email protected]
1 years ago (2017-11-26)
-
doc.z
bin***[email protected]
It should be noted that the execution order of SKIP, sort and limit here has nothing to do with their positions, but when they are used in aggregate, they have the characteristics of pipeline flows and are executed in the order of their positions.
Directing a sort
Directing the sort () method
In MongoDB, sort() method is used to sort data, sort() method can specify the sorted field by parameter, and use 1 and -1 to specify the sorting method, where 1 is ascending and -1 is descending.
grammar
The basic syntax of the sort() method is as follows:
>db.COLLECTION_NAME.find().sort({KEY:1})
Copy the code
The instance
The col set contains the following data:
{"_id" : ObjectId("56066542ade2f21f36b0313a"), "title" : "PHP tutorial ", "description" : "PHP is a powerful server-side scripting language for creating dynamic, interactive sites." Rookie tutorial, "by" : ""," url ":" http://www.runoob.com ", "tags" : [" PHP "], "likes" : 200} {" _id ": ObjectId(" 56066549ade2f21F36B0313b "), "title" : "Java tutorial ", "description" : Java is a high-level programming language introduced by Sun Microsystems in May 1995. Rookie tutorial, "by" : ""," url ":" http://www.runoob.com ", "tags" : [" Java "], "likes" : 150} {" _id ": ObjectId(" 5606654FAde2f21f36B0313c "), "title" : "MongoDB tutorials ", "description" : "MongoDB is a Nosql database ", "by" : "Rookie tutorial", "url" : "http://www.runoob.com", "tags" : [" mongo "], "likes" : 100}Copy the code
The following example demonstrates the descending order of data in the COL collection for the field likes:
> db. Col. Find ({}, {" title ": 1, _id: 0}), sort ({" likes" : 1}) {" title ":" PHP tutorial "} {" title ":" the Java tutorial "} {" title ": "MongoDB tutorial "} >Copy the code
MongoDB Limit and Skip methods
Directing index
Write notes
-
niuyongjie
niu***[email protected]
When skip(), limilt(), and sort() are executed together, the order is sort(), then skip(), and finally limit() displayed.
Directing index
Indexes can greatly improve query efficiency. If there is no index, MongoDB must scan every file in the collection and select the records that meet the query conditions when reading data.
The query efficiency of scanning the whole collection is very low, especially when dealing with a large amount of data, the query can take tens of seconds or even a few minutes, which is very fatal to the performance of the website.
An index is a special data structure that is stored in a collection of data that is easy to traverse and read. An index is a structure that sorts the values of one or more columns in a database table
CreateIndex () method
MongoDB uses the createIndex() method to create the index.
Note indexes to be created before the 3.0.0 release method for the collection. The ensureIndex (), after version USES the db. Collections. CreateIndex () method, ensureIndex () can also be used, But this is just an alias for createIndex().
grammar
The basic syntax of the createIndex() method is as follows:
>db.collection.createIndex(keys, options)
Copy the code
In the syntax, the Key value is the index field that you want to create. 1 is used to create the index in ascending order. -1 is used if you want to create the index in descending order.
The instance
>db.col.createIndex({"title":1})
>
Copy the code
You can also set the createIndex() method to create indexes with multiple fields (called compound indexes in relational databases).
>db.col.createIndex({"title":1,"description":-1})
>
Copy the code
CreateIndex () accepts optional parameters, which are listed as follows:
Parameter | Type | Description |
---|---|---|
background | Boolean | The index creation process blocks other database operations. Background specifies how to create an index in the background. “Background” defaults tofalse. |
unique | Boolean | Whether the created index is unique. Specifies true to create a unique index. The default value isfalse. |
name | string | The name of the index. If not specified, MongoDB generates an index name from the join index’s field name and sort order. |
dropDups | Boolean | Version 3.0+ is not available. Whether to delete duplicate records when creating unique indexes, specifying true to create unique indexes. The default value isfalse. |
sparse | Boolean | Disable indexing for field data that does not exist in the document; This parameter is important because if set to true, documents that do not contain the corresponding field will not be queried in the index field. The default value isfalse. |
expireAfterSeconds | integer | Specify a value in seconds to complete the TTL setting and set the lifetime of the collection. |
v | index version | The version number of the index. The default index version depends on the version mongod was running when the index was created. |
weights | document | Index weight value. The value between 1 and 99,999 represents the score weight of this index relative to other index fields. |
default_language | string | For text indexing, this parameter determines the list of stop terms and rules for stems and lexical devices. Default: English |
language_override | string | For text indexes, this parameter specifies the name of the field to be included in the document, overriding the default language, which is language. |
The instance
Create index in the background:
db.values.createIndex({open: 1, close: 1}, {background: true})
Copy the code
Make the creation work in the background by adding the background:true option to the index creation
-
1. View the collection index
db.col.getIndexes() Copy the code
2, check the set index size
db.col.totalIndexSize() Copy the code
Drop all indexes in the set
db.col.dropIndexes() Copy the code
Drop the set index
Db.col.dropindex (" index name ")Copy the code
onroad
onroad
liu***[email protected]
5 months ago (11-20)
-
Ling feather st
664***[email protected]
Refer to the address
Use TTL set to set the expiration time of stored data: after a specified time period or expiration point, independent MongoDB thread will clear the data. Similar to setting a scheduled automatic deletion task, you can clear historical records or logs. Set the key field of Index to the Date type new Date().
For example, when createDate is a date in a data record:
- This parameter is automatically cleared after 180 seconds.
- Delete a record in about 180 seconds after it is created.
db.col.createIndex({"createDate": 1},{expireAfterSeconds: 180}) Copy the code
Cleared by a set date point in the record.
Set record A to be deleted at around 11 PM on January 22, 2019. Add “ClearUpDate” to record A: New Date(‘Jan 22, 2019 23:00:00’) and expireAfterSeconds in Index set to 0.
db.col.createIndex({"ClearUpDate": 1},{expireAfterSeconds: 0}) Copy the code
Other notes:
- The index key field must be of type Date.
- Non-immediate execution: The Document expiration data is scanned and deleted by an independent thread. By default, it is scanned once in 60s, and deletion may not be immediately successful.
- Single-field index, mixed index is not supported.