MongoDB Basic Tutorial Series--The third MongoDB fundamental operation (ii)

Source: Internet
Author: User

1. Set operation

1.1. Create a collection

MongoDB creates a collection with the Db.createcollection (name, options) method.

Format

Db.createcollection (name, options)

Where name is the collection name, is a string, options is optional, is a document, specifies memory size and index options, and the specific parameters are described in the following table:

Field type Description
Capped Boolean (optional) If true, represents a fixed collection. A fixed collection is a collection that has a fixed amount of storage space.
When this value is true, you must specify the size parameter.
Autoindexid Boolean (optional) If true, the index is automatically created in the _id field. The default is False.
Size Numerical Optionally, specify a maximum value ( in bytes ) for the fixed collection.
If capped is true, you also need to specify the field.
Max Numerical Optionally, specify the maximum number of documents for the fixed collection.

Note: 1. If the maximum number of documents (max) is reached before collection reaches the maximum storage limit (size), the old document is deleted.

2.MongoDB checks the size value before checking the max value

Example

Create a Collection "user", create an index for the field _id, maximum storage space is 10M, maximum number of documents is 1000

>db.createcollection ("user", {capped:true, autoindexid:true, size:10485760, max:1000}) {"OK": 1}>

Description

In MongoDB, you can create a collection without the CreateCollection () method, because the collection is created automatically when you insert the document

>db.mycollection.insert ({"Name": "Liruihuan"}) Writeresult ({"ninserted": 1}) >show Collections              Mycollectionuser>

Where show collections represents all the collections in the current operations database.

1.2. Deleting a collection

MongoDB deletes a collection with Db.collection.drop ()

Format

Db. Collection_name.drop ()

True if delete succeeds, otherwise, false is returned

Example

Delete the MyCollection collection that you just created and display the deleted collection list to verify that the deletion was successful

>db.mycollection.drop () True>show collectionsuser>
2. Document Operation

2.1. Inserting documents

MongoDB inserts a document into the collection with insert () or save ()

Format

Db.collection.insert (document)

Example

We insert {"name" into the collection "user": "user1", "Age": 19} Document, first query the document that exists in the collection "user" before inserting, and then query all the documents that are inserted later to determine whether the insert succeeds

> Db.user.find () {"_id": ObjectId ("58e1d2f0bb1bbc3245fa754b"), "name": "Liruihuan", "Age":}> Db.user.insert ({ "Name": "User1", "Age": +}) Writeresult ({"ninserted": 1})    # Insert a data > Db.user.find () {"_id": ObjectId (" 58e1d2f0bb1bbc3245fa754b ")," name ":" Liruihuan "," age ": {" _id ": ObjectId (" 58e1d2f0bb1bbc3245fa754c ")," name ":" Us Er1 "," Age ":}>

The document query uses the Find () method, which is explained in detail in the next article.

You can also use the Db.collection.save (document) command to insert documents. If you do not specify the _id field, the Save () method is similar to the Insert () method. If the _id field is specified, the data for the _id is updated. The Save () method is illustrated in the following update document.

2.2. Update the documentation

MongoDB updates the document in the collection with update () or save ()

2.2.1, update ()

Update () Updates the value of the document already exists

Format

Db. Collection_name.update (Selectioin_criteria, Updated_data)

Example

In the collection "User", update the original name value "user1" of the document to "User2", before updating the document that exists in the collection "user" before querying all subsequent documents to determine whether the update was successful

> Db.user.find () {"_id": ObjectId ("58e1d2f0bb1bbc3245fa754b"), "name": "Liruihuan", "age": {"_id": ObjectId ("5 8e1d2f0bb1bbc3245fa754c ")," name ":" User1 "," Age ":}>db.user.update ({' name ': ' User1 '},{$set: {' name ': ' User2 '}}) Writeresult ({"nmatched": 1, "nupserted": 0, "nmodified": 1})   # output Info > Db.user.find () {"_id": ObjectId ("58e1d2f 0bb1bbc3245fa754b ")," name ":" Liruihuan "," age ": {" _id ": ObjectId (" 58e1d2f0bb1bbc3245fa754c ")," name ":" User2 "," Age ": 19}

The above example will only update the first found document, if you want to update all the found documents, you need to use Multi:true, as follows

Db.user.update ({' name ': ' User1 '},{$set: {' name ': ' User2 '}},{multi:true})

The update operator $set is used above, among others: $inc, $unset, $push, $ne, and so on. Interested partners can search the web for specific meanings.

2.2.2, Save ()

The Save () method replaces an existing document with an incoming document.

Format

Db. Collection_name.save ({_id:objectid (), new_data})

Example

Replace the original document with _id = ' 58e1d2f0bb1bbc3245fa754b ' document, query the document that exists in the collection "user" before updating, and then query all subsequent documents to determine whether the update was successful

> Db.user.find () {"_id": ObjectId ("58e1d2f0bb1bbc3245fa754b"), "name": "Liruihuan", "Age": >db.user.save (
   {      "_id": ObjectId ("58e1d2f0bb1bbc3245fa754b"), "name": "User3", "Age":   ()) Writeresult ({"nmatched": 1, " Nupserted ": 0," nmodified ": 1})   

2.3. Deleting documents

MongoDB removes the document from the collection with remove ()

Format

Db. Collection_name.remove (Delletion_critteria,justone)

Justone if set to TRUE or 1, only one document is deleted.

Example

Delete the document named ' User1 ' before deleting the document that exists in the collection "user" before querying all documents after deletion to determine if the deletion was successful

> Db.user.find () {"_id": ObjectId ("58e1d2f0bb1bbc3245fa754b"), "name": "Liruihuan", "age": {"_id": ObjectId ("5  8e1d2f0bb1bbc3245fa754c ")," name ":" User1 "," Age ":} {" _id ": ObjectId (" 58e1d2f0bb1bbc3245fa754d ")," name ":" User1 ", "Age":}>db.user.remove ({"Name": "User1"}) Writeresult ({"Nremoved": 2})      

If you want to delete only one record, you need to set Justone to 1, as follows:

Db.user.remove ({"Name": "User1"},1)

If you want to delete all records, you can write this

Db.user.remove ({})

Diligence, desolate and journeys by chance, destroyed by the following.

If you think this article is good or helpful to you, you can give bloggers a little encouragement and support through the "reward" function on the right.

MongoDB Basic Tutorial Series--The third MongoDB fundamental operation (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.