MongoDB database document CRUD operation tutorial, mongodbcrud

Source: Internet
Author: User
Tags mongodb query

MongoDB database document CRUD operation tutorial, mongodbcrud
MongoDB document CRUD operation query documentBasic usageThe syntax of the mongodb query document is as follows :?

Db. collection_name.find (query, projection )? ? ? ? ? # Return data in compressed format
Db. collection_name.find (query, projection). pretty ()? # Returning data in readable format
Query: Optional. Use the query operator to specify query conditions;
Projection: (optional) specifies the return key using the projection operator. to return all the keys in the document, you only need to omit this parameter;?
# Query all documents in the testdb. artciles set
> use testdb
> db.articles.find().pretty() ? ?
?
# Query the author = 'assad 'Document in the testdb. articles set
> db.atricles.find( { author:'assad' } )

Query condition Operator

Operator

Meaning and syntax Example
Comparison query operator
: Equal to (= );
{ : }
Db. col. find ({name: 'assad '?} )
Query documents with name = 'assad'
$ Ne Not equal (! = );
{ : {$ Ne: }}
Db. col. find ({name: {$ ne: 'assad '}})
Query name! = 'Assad 'Document
$ Lt Less than (<):
{ : {$ Lt: }}
Db. col. find ({score: {$ lt: 120 }})
Query documents with score> 120
$ Gt Greater than (> );
{ : {$ Gt: }}
Db. col. find ({score: {$ gt: 120 }})
Query documents with score <120
$ Lte Less than or equal to (<= );
{ }}
Db. col. find ({score: {$ lte: 120 }})
Query documents with score <= 120.
$ Gte Greater than or equal to (> = );
{ : {$ Gte: }}
Db. col. find ({score: {$ gte: 120 }})
Query documents with score> = 120
Logical Link query operator
$ And? And relationship;
{$ And: [query1, query2]}
{Query1, query2}
Db. col. find ({$ and: [{city: 'guangzhou'}, {score: {$ gt: 250})
Db. col. find ({city: 'guangzhou ',? Score :{$ gt: 250 }}?
Query the city = 'guangzhou' and core> 250 documents?
$ Or Or relationship;
{$ Or: [query1, query2]}
Db. col. find ({$ or: [{city: 'guangzhou'}, {score: {$ gt: 250})
Query the city = 'guangzhou' or core> 250 documents?
$ Nor Nor exclusive or link;
{$ Nor: [query1, query2]}
Db. col. find ({$ nor: [{city: 'guangzhou'}, {score: {$ gt: 250})
Query (city = 'guangzhou' or core <= 250) and (city! = 'Guangzhou' and core> 250?
$ Not Non-relational;
{$ Not: {query }}
Db. col. find ({$ not: {city: 'guangzhou '}})
Query city! = 'Guanhgzhou' document
Member relationship query operator
$ All Query the results of key matching all members in the specified array;
{ :{$ All: [array]}
Db. col. find ({tages: {$ all: ['java', 'cpp ', 'linux']})
Query documents that contain all the values 'java', 'cpp ', and 'linux' in the tages field array.
$ In? Queries the results of key matching any member in the specified array;
{ :{$ In: [array]}
Db. col. find ({tages: {$ in: ['java', 'cpp ', 'linux']})
Query documents with any value in the tages field array including 'java', 'cpp ', and 'linux'
$ Nin The query key does not match any member in the specified array;
{ :{$ In: [array]}
Db. col. find ({tages: {$ in: ['java', 'cpp ', 'linux']})
The query tages field array does not contain documents with 'java', 'cpp ', and 'linux '.
. The query key specifies the subscript member, and the index starts from 0;
{ : Query}
Db. col. find ({tages.1: 'java '})
Query the tages field array documentation with 2nd elements = 'java'
Value Attribute query operator
$ Size Queries an array of the specified length.
{ :{$ Size: value }}
Db. col. find ({tages: {$ size: 3 }})
Query documents whose tages field array length is 3, which can be used in combination with the comparison query operator
$ Type Query keys of the specified type. For details about the types, see:
Https://docs.mongodb.com/manual
/Reference/operator/query/type/index.html
{ :{$ Type: typecode }}
Db. col. find ({title: {$ type: 2 }})
Query documents with the title type of String
$ Exits Query a document with a specified key
{ : {$ Exists: }}
Db. col. find ({school :{$ exits: false }})
Query all documents without the school field
Null Not an operator, but a placeholder for a null value.
{ : Null}
{ :{$ In: [null]}
Db. col. find ({school: null })
Query documents whose school field does not exist or whose school field value is null
Db. col. find ({school :{$ in: [null], $ exists: true }})
Query documents whose school field exists but whose value is null
$ Regex Regular matching of strings. Using perl-compatible expressions, you can use SQL like clauses;
{ :{$ Regex: pattern, $ options: ops }}

$ Options is used to modify regex. The parameters are as follows:
-I: case insensitive;
-X: forces the branch of a string that is not labeled with \ n;
-S: the dot in pattern matches all characters (including line breaks );
-X: special characters not escaped in pattern are ignored;
Db. col. find ({name: {$ regix: "^ *"}})
Db. col. find ({name:/^ */}})
Query documents whose names start with

Db. col. find ({name: {$ regex: "^ a *", $ options: 'I '}})
Db. col. find ({name:/^ a */I })
Query documents whose names start with a, or are case-insensitive.
$ Where Use any JavaScript as part of the query, including Js expressions and Js closures;
{$ Where: javascript-operation}
In Js expressions, this and obj are used to represent each document object.
Db. col. find ({$ where: "this. score> this. salary "})
Db. col. find ({$ where: "obj. score = this. salary "})
Db. col. find ({$ where: function () {return (this. score> this. salary )}})
Query all score> salary documents in col;

?
> use testdb
# Query the author = "assad" document in the testdb. articles set
> db.articles.find( { author:'assad' } )
?
# Query likes> 1000 documents
> db.articles.find( { likes:{$gt:1000} } )
?
# Query documents with likes greater than 1000 and less than 1500
> db.artciles.find( { likes:{$gt:1000, $lt:1500} } )
?
# Query author = "assad" likes> 2000 documents at the same time
> db.articles.find( { author:'assad', likes:{$gt:2000} } )
?
# Query authoer = "assad" or "vancy" Documents
> db.articles.find( { author:{$in:['assad','vancy']} } )
?
# Query documents whose tages array contains both 'java' and 'groovy'
> db.articles.find( { tages:{ $all:['java','groovy']} } )
?
# Querying the title containing the 'java' Field

Query return result Processing Use the projection parameter of the find () function to limit the return key?
# Query all documents in the testdb. article set. Only the title and author keys are returned. The _ id keys are returned by default)
> db.articles.find( {}, {title:1, author:1} )
{ "_id" : ObjectId("5a83c281a04c12209d79eea3"),"title" : "groovy refrence","author" : "assad" }
{ "_id" : ObjectId("5a83c5a0a04c12209d79eea4"),"title" : "spring refrence","author" : "alex" }
?
# Same as above. The _ id key is not returned.
> db.articles.find( {}, {title:1, author:1, _id:0} )
{ "title" : "groovy refrence", "author" : "assad" }
{ "title" : "spring refrence", "author" : "alex" }
$ Slice OperatorUse the $ slice operator to limit the number of returned documents ;?
# Return the first 20 documents
> db.articles.find( {}, { _id:{$slice:20} } )
# Return the first 20 documents containing titles
> db.articles.find( {}, { titles:{$slice:20} } )
?
# Return 10 items that contain titles after 20th items;
> db.articles.find( {}, { titles:{$slice:[ 20, 10 ]} } )
# Return 10 items that contain titles after the last 20th items;
> db.articles.find( {}, { titles:{$slice:[ -20, 10 ]} } )
Skip (), limit () method
The above uses the $ slice operator to limit the number of displayed results. You can use the skip () and limit () functions instead ;?
# Return the first 20 documents
> db.articles.find().limit(20)
# Return 10 items after 20th items;
> db.articles.find().skip(20).limit(10)
Sort () method
The sort () method is used to sort the query results. The prototype of the method is as follows, where the key is sorted by the key, 1 indicates the forward direction, and-1 indicates the reverse direction:
Db. colletion_name.find (). sort ({ : <1 |-1> }) ?
# Return results are sorted in the likes positive order
> db.artciles.find().sort(likes:1)
?

Query embedded documentsMongo performs the same query and Array Operations on embedded documents, for example :?
{ 
 ?  _id : ObjectId("51d7b0d436332e1a5f7299d6"),
 ? ?"name" : {
 ? ? ? ?"first" : "Van",
 ? ? ? ?"last" : "Darkholme"
 ? ? },
 ? ? "comments" : "Deep Dark Fanstatic"
}
Where is the value of "name" an embedded document?
# Query the document name. first = "Van"
> db.nobodyknown.find( { name: {first:"Van"} } );
# Query documents whose name. first = "Van", name. last includes "Dark"
> db.nobodyknown.find( { name:{first:"Van", last:{$regex:"*Dark*"}} } )
Query grouping and data aggregation mongodb if you implement statistical aggregation methods such as group clause, count (), avg () in SQL queries, you can use the aggregation method aggregate () For details, see 06. mongoDB data aggregation


Insert document mongodb inserts a document using the insert () method. The syntax is as follows :?
db.collection_name.insert(document)
Example:
?
# Insert a record in the articles set in the testdb Database
> use testdb
>  db.articles.insert({
... title:'groovy refrence',
... author:'assad',
... tages:['groovy','java'],
... like:2333
... })
Insert date typeYou can use new Date () to create a value of the Date type. The following is an example :?
# Insert the current time value
>  db.logdate.insert( { ip:'255.33.21.36', logDate:new Date() } ) ?
.....
# Insert a specified time value
> Db. logdate. insert ({ip: '2017. 33.21.36 ', logDate: ISODate ('2017-02-12 15:33:00 ')})? # Specified time
Update document Update () methodThe update () method is used to update an existing document. The syntax is as follows:
?
db.collection_name.update( 
 
  , 
  
   , { upset:
   
    , muti:
    
     ,writeConcern:
     
      } )
     
    
   
  
 
Query: the query condition of the update statement. The detailed syntax is the same as that of the query parameter (which can be understood as the where clause of SQL update );
Update: The updated object and some updated operators, such as the $ set operator (which can be understood as the set clause of SQL update ); Upset: Optional. It indicates whether to insert a new document object if no update record exists. The default value is false;
Muti: Optional. "true" indicates that all searched documents are updated. "false" indicates that only the first searched document is updated. The default value is "false;
WriteConsern: (optional) indicates the level of the thrown exception;The common operators in update are as follows:
Operator Meaning and syntax Example
$ Set Set the value of a key to another value.
{$ Set :{ : , : ,...}}
Db. col. update ({name: 'assad '}, {$ set: {name: 'assad2 '}})
Update the name of the document with name = 'assad 'to 'assad2'
$ Inc Perform auto-increment on the value of a key (using a negative number to represent auto-subtraction)
{$ Inc :{ :, :,...}}
Db. col. update ({name: 'assad '}, {$ inc: {score: 10 }})
Score + 10 of the document name = 'assad'
Example :?
> use testdb
# Set the title of the author = 'assad 'document to 'huaq! '
> Db. articles. update ({name: 'assad '}, {$ set: {title: 'huaq! '}})
?
# Set score> = 2500 to score-100, level + 5
> db.users.update( {score:{$gte:250}}, {$inc:{score:-100, level:5}} )
The save () method replaces existing documents with the imported documents. The syntax is as follows :?
db.collection.save( 
 
  , { writeConcern: 
  
    } )
  
 
Example :?
>db.article.save({
 ? ?"_id" : ObjectId("56064f89ade2f21f36b03136"),
 ? ?"title" : "MongoDb",
 ? ?"author" : "assad",
 ? ?"tags" : [
 ? ? ? ? ? ?"mongodb",
 ? ? ? ? ? ?"nosql"
 ?  ],
 ? ?"likes" : 110
})


Delete a document mongodb uses the remove () method to delete the document. The syntax is as follows :?
db.collection.remove( 
 
  , { justOne:
  
   , writeConcern:
   
     )
   
  
 
Query: (optional) Conditions for deleting a document;
JustOne: (optional) Delete only one document if set to true or 1 ';
WriteConcern: (optional) exception level thrown;
Example :?
# Delete all author = "assad" documents in the article set
> db.artciles.remove( {author:'assad'},{justOne:false} )
?
# Deleting all documents in the artciles set
> db.articles.remove( {},{justOne:false} )

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.