MongoDB Learning (ii)

Source: Internet
Author: User
Tags mongodb query

Common statements:

To Create a database: Use database_name

Example: Use Myfisrtmongodb

Shell tip: Switched to DB MYFISRTMONGODB indicates success

However, with the show DBS command, you will not be able to see the newly created database, you need to insert the first data before you can view it.

To Delete a database: db.dropdatabase ()

The command is to delete the current database

Hint: {"Dropped": "Myfirstmongodb", "OK": 1}

inserting documents:Db.collections_name.insert (document)

Represents a document inserted in the collection named Collections_name in the current database

Example: Db.cols.insert ({"Content": "Myfirstrecorder", "by": "Insanexs"})

After the record insertion is complete, you can view all the records (documents) in the collection named Collections_name under the database by using the Db.collections_name.find () command.

We can also define the data as a variable and then insert it through the above command

Example: Document_name = {"Content": "Insertbydocumentvar"}

Db.cols.insert (Document_name)

A document variable named Document_name is defined, and the document variable is inserted into the collection.

To update a document: MongoDB updates a document in two ways, update () and save ()

The syntax format for update ():

db.collections_name.update (criteria, objnew, Upsert, Multi, Writeconcern)

Criteria: Standard, which is the query condition, equivalent to the WHERE statement in the SQL statement

Objnew:update objects and some updated operators (such as $, $inc ... ) can also be understood as part of the SQL update query within the set

Upsert:boolean type, optional, indicates whether the document is inserted when the document does not exist, true indicates insert, and the database defaults to False

Multi:boolean type, optional, indicates whether all records are updated when multiple records are met, True indicates that all records are updated, and the database defaults to False

Writerconcert: Optional, indicating the level at which the exception was thrown

Example:

Db.cols.update ({"Content": "Insertbydocumentvar"},{$set: {"Content": "Recorderupdatebyupdate"},true,true})

Significance:

Updates a document with a content value of Insertbydocumentvar in the Cols collection under the current database all to the set document (if the field exists, the update value is not present, the field is incremented before), and if it does not exist, the document is inserted.

Save (): Replaces an existing document with an incoming document

Db.collections.save (x), X is the document to be updated, MongoDB finds the document to be updated in the database based on the value of X's _id, and inserts the document if it does not exist.

Example:

Db.cols.save ({"_id": ObjectId ("56a860650c412f8aa5c4c25a"), "content": "Updaterecorderbysave"})

Meaning: Replace the document with the ID "56a860650c412f8aa5c4c25a" in the Cols collection under the DB database (because the document is replaced, so if the new document does not contain other fields of the old document, the other fields will be deleted.) ), no inserts the record (the ID will not be automatically generated when the insert, but is the value of the ID).

Update operators in MongoDB

$inc Add a Val value to an int field

{$inc: {Filed:value}}

Example:

Db.cols.update ({"Count": 1},{$inc: {"Count": 1}})

Significance: Adds 1 to the Count field in the Cols collection of the current database in the document count equals 1

$set Set field = value equivalent to SQL, all data types support

Usage: {$set: {Field:value}}
Example: Refer to the beginning of the article

$unset Delete a field

Usage: {$unset: {Filed:value}}

The database first inserts a data db.cols.insert{"filed1": "1", "Filed2": "2"};

Example: Db.cols.update ({"filed1": "1"},{$unset: {"Filed2": "2"}})

Use Db.cols.find (). Pretty () query

See the result: {"_id": ObjectId ("56a874310c412f8aa5c4c261"), "field1": "1"}

$push Appends a value to the specified filed, the field must be an array

Usage: {$push: {Filed:value}}

Example:

The database first inserts a data db.cols.insert{"MyArray": ["a", "B"], "Count": 1}

Db.cols.update ({"Content": 1},{$push: {"C"}})

In the query collection, you see the results:

"_id": ObjectId ("56A877EC04D77A4FE6E85FFB"),
"Count": 1,
"MyArray": [
"A",
"B",
C
]

$pushAll is similar to $push, except that $pushall can append multiple values to an array field

Usage: {$pushAll: {Field:array}}

The example above, do not repeat, but note that the field value must be an array

$addToSet Add this value to the array only if a value is no longer in the array

Usage: {$addToSet: {Field:value}}

For example, field must be an array.

$pop Delete a value in an array

Usage:

Delete the last value of the array: {$pop: {field:1}}

Delete Array Header value: {$pop: {field:-1}}

$pull Remove the value value from the array in field

Usage: {$pull: {Filed:value}}

Same as above, if there are multiple values for value, delete all

$pullAll Remove the value from the array in the array from the field

Usage: {$pull: {Filed:array}}

Usage Ibid.

The $ operator is the one that finds itself in the array.

Because the filed value of the item is obtained, enclose the quotation mark (The Scarlet Letter part).

Take a look at the official example:
> T.find ()
{"_id": ObjectId ("4b97e62bf1d8c7152c9ccb74"),"title":"ABC","Comments": [{"by":"Joe","votes": 3}, { "by": "Jane", "votes": 7}]}

> t.update ({ ' comments.by ': ' Joe ' }, {$inc: { ' comments.$.votes ' : 1}, false, true)

> T.find ()
{ "_id": ObjectId ( "4b97e62bf1d8c7152c9ccb74"), "title": "ABC", "comments": [{ "by": "Joe", "votes": 4 }, { "by": " votes ": 7}]}

It is important to note that $ will only be applied to the first array item found, followed by no matter. The
also needs to be aware that the $ and $unset union use will leave a null record in the array > T.insert ({x: [1,2,3,4,3,2,3,4]}> T.find ({ "_id": ObjectId ("4bde2ad3755d00000000710e"), "x": [1, 2, 3, 4, 3, 2, 3, 4]} > T.update ({x:3}, {$unset: {"x.$": 1}})
> T.find ()
{ "_id": ObjectId ("4bde2ad3755d00000000710e"), "x": [1, 2, null, 4, 3, 2, 3, 4]}


MongoDB Delete document :db.collection_name.remove ()
Usage: db.collection_name.remove (query, Justone)
Query: Query condition
Justone: Indicates if there are multiple records to be deleted at the same time, optional, The default is False

to delete all documents in a collection: Db.collection_name.remove ({})
deletes only the first qualifying element: Db.collection_name.remove ({condition},1)


mongodb Query document: db.collection_name.find ()
Format the query result: Db_collection_name.find (). Pretty ()

and condition query:
Usage: db.collection_name.find ({filed1:value,field2:value ...})

or condition query:
Usage: db.collection_name.find ({$or: [{filed:value},{field:value}]});
An or conditional query is like placing multiple conditions in an array and then composing a document by that array, while the and condition query is a document that is directly formed by each condition.


Reference: http://www.runoob.com/mongodb/mongodb-tutorial.html

MongoDB Learning (ii)

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.