MongoDB Tutorial Data Manipulation Example _mongodb

Source: Internet
Author: User
Tags bulk insert comments findone modifier mongodb mongodb tutorial

1. BULK INSERT:

Inserting multiple documents one at a time in an array can be done in a single TCP request, avoiding additional overhead in multiple requests. In terms of data transfers, the bulk-inserted data contains only one message header, and multiple single inserts encapsulate the message header data each time the data is inserted. For data import, we can use Mongoimport to complete.

2. Database cleanup:

Copy Code code as follows:

> Db.users.remove ()



The above command clears all data in the Users collection, but does not delete the collection itself and the associated index. The data deletion operation is not recoverable and is physically deleted once the deletion is made. A more efficient way to eliminate this case for the complete collection is to delete the collection object itself and all the indexes associated with it, and then rebuild it sequentially, for example:


Copy Code code as follows:

> Db.one_collection.drop ()






3. Data Update:

If more than one document matches the update criteria when performing a data update, MONGODB will update only the first query results, in order to avoid a recurring conflict with the updated _id, such as:

Copy Code code as follows:

> post1 = {"Name": "Stephen", "Age": "35"}
{' name ': ' Stephen ', ' Age ': ' 35 '}
> post2 = {"Name": "Stephen", "Age": 36}
{' name ': ' Stephen ', ' Age ': 36}
> Db.blog.insert (POST1)
> Db.blog.insert (POST2)
> post3 = {"Name": "Stephen", "Age": 37}
{' name ': ' Stephen ', ' Age ': 37}
> db.blog.update ({"Name": "Stephen"},post3)
> Db.blog.find ()
{"_id": ObjectId ("4fcd7e2e20668578cc1097d8"), "name": "Stephen", "Age": 36}
{"_id": ObjectId ("4fcd7e2820668578cc1097d7"), "name": "Stephen", "Age": 37}






4. Modifying device:

Data updates using the modifier are both atomic and efficient, unlike all documents where the _id of the updated document does not change, and a full update of the document modifies the _id of the document and the associated index.

Copy Code code as follows:



> Db.blog.find ()


{"_id": ObjectId ("4fcd7e2820668578cc1097d7"), "name": "Stephen", "Age": 41}


{"_id": ObjectId ("4fcd81bb20668578cc1097d9"), "name": "Stephen", "Age": 38}


--$inc modifier adds one to the age key atom of the document that matches the criteria, and by default only updates the first qualifying document.


> db.blog.update ({"Name": "Stephen"},{"$inc": {"Age": 1}})


> Db.blog.find ()


{"_id": ObjectId ("4fcd7e2820668578cc1097d7"), "name": "Stephen", "Age": 42}


{"_id": ObjectId ("4fcd81bb20668578cc1097d9"), "name": "Stephen", "Age": 38}


-You can specify that all eligible documents are updated by using the last parameter of the update function, such as:


> db.blog.update ({"Name": "Stephen"},{"$inc": {"age": 1}},true,true)


> Db.blog.find ()


{"_id": ObjectId ("4fcd7e2820668578cc1097d7"), "name": "Stephen", "Age": 43}


{"_id": ObjectId ("4fcd81bb20668578cc1097d9"), "name": "Stephen", "Age": 39}

--$set modifier to directly modify the content of the matching document, if the modified key exists directly modify, otherwise Add.


> db.blog.update ({"Name": "Stephen"},{"$set": {"Genda": "Male"}})


> Db.blog.find ()


{"_id": ObjectId ("4fcd88b720668578cc1097da"), "Age": "A", "Genda": "Male", "name": "Stephen"}


--$unset Modify the $set function is completely reversed, such as:


> db.blog.update ({"Name": "Stephen"},{"$unset": {"Genda": "Male"}})


> Db.blog.find ()


{"_id": ObjectId ("4fcd88b720668578cc1097da"), "Age": "A", "name": "Stephen"}


-You can modify the nested subdocument by $set modifier.


> Db.blog.find ()


{"_id": ObjectId ("4fcd8e0220668578cc1097db"), "title": "A Blog Post", "author": {"name": "Joe", "email": "joe@ee.co M "}}


> db.blog.update ({"title": "A blog Post"},{"$set": {"Author.name": "Joe Schmoe"})


> Db.blog.find ()


{"_id": ObjectId ("4fcd8e0220668578cc1097db"), "author": {"email": "joe@ee.com", "name": "Joe Schmoe"}, "title": "A Blog Post "}





5. Array modifier:

Copy Code code as follows:



> Db.blog.insert ({"title": "One Blog"})


> Db.blog.find ()


{"_id": ObjectId ("4FCD909520668578CC1097DC"), "title": "One Blog"}


--Creates a new key value with the type of the value as an array type if the key of the action does not exist.


> log.update ({"title": "One Blog"}, {"$push": {"comments": {"Content": "" Hello}}})


> Db.blog.findOne ()


{


"_id": ObjectId ("4FCD909520668578CC1097DC"),


"Comments": [


{


"Content": "Hello"


}


],


"title": "One Blog"


}


--If the key value of the $push operation already exists and its value is an array type, the modifier adds a new array element to the array.


> db.blog.update ({"title": "One Blog"}, {"$push": {"comments": {"content": {"word"}}


> Db.blog.findOne ()


{


"_id": ObjectId ("4FCD909520668578CC1097DC"),


"Comments": [


{


"Content": "Hello"


},


{


"Content": "word"


}


],


"title": "One Blog"


}





> post = {"username": "Joe", "emails": ["joe@example.com", "joe@gmail.com", "Joe@yahoo.com"]}


{


"username": "Joe",


"Emails": [


"Joe@example.com",


"Joe@gmail.com",


"Joe@yahoo.com"


]


}


> Db.blog.insert (POST)


> Db.blog.findOne ()


{


"_id": ObjectId ("4fd2e468b2ac404941134bed"),


"username": "Joe",


"Emails": [


"Joe@example.com",


"Joe@gmail.com",


"Joe@yahoo.com"


]


}


--$addToSet applies to arrays, if the element already exists in the array, the command returns without any action, or inserts the new element into the array.


> db.blog.update ({"username": "Joe"}, {"$addToSet": {"emails": "Joe@gmail.com"}})


> Db.blog.findOne ()


{


"_id": ObjectId ("4fd2e468b2ac404941134bed"),


"username": "Joe",


"Emails": [


"Joe@example.com",


"Joe@gmail.com",


"Joe@yahoo.com"


]


}


> db.blog.update ({"username": "Joe"}, {"$addToSet": {"emails": "Joe@hotmail.com"}


> Db.blog.findOne ()


{


"_id": ObjectId ("4fd2e468b2ac404941134bed"),


"Emails": [


"Joe@example.com",


"Joe@gmail.com",


"Joe@yahoo.com",


"Joe@hotmail.com"


],


"username": "Joe"


}


--a combination of $addToSet and $each can insert an array into another array.


> db.blog.update ({"username": "Joe"},{"$addToSet": {"emails": {"$each": ["Joe@php.net", "Joe@example.com"]}})


> Db.blog.findOne ()


{


"_id": ObjectId ("4fd2e468b2ac404941134bed"),


"Emails": [


"Joe@example.com",


"Joe@gmail.com",


"Joe@yahoo.com",


"Joe@hotmail.com",


"Joe@php.net"


],


"username": "Joe"


}


--$pop Remove an element from an array, such as a parameter of 1, that deletes an element from the end of the array and, if it is-1, removes it from the head.


> db.blog.update ({"username": "Joe"}, {"$pop": {"emails": 1}})


> Db.blog.findOne ()


{


"_id": ObjectId ("4fd2e468b2ac404941134bed"),


"Emails": [


"Joe@example.com",


"Joe@gmail.com",


"Joe@yahoo.com",


"Joe@hotmail.com"


],


"username": "Joe"


}


> db.blog.update ({"username": "Joe"}, {"$pop": {"emails":-1}})


> Db.blog.findOne ()


{


"_id": ObjectId ("4fd2e468b2ac404941134bed"),


"Emails": [


"Joe@gmail.com",


"Joe@yahoo.com",


"Joe@hotmail.com"


],


"username": "Joe"


}


--$pull modifier deletes the specified element from the data


> db.blog.update ({"username": "Joe"}, {"$pull": {"emails": "Joe@yahoo.com"}})


> Db.blog.findOne ()


{


"_id": ObjectId ("4fd2e468b2ac404941134bed"),


"Emails": [


"Joe@gmail.com",


"Joe@hotmail.com"


],


"username": "Joe"


}


--Make duplicate elements appear in the array to facilitate the functional presentation of the later modifier.


> db.blog.update ({"username": "Joe"}, {"$push": {"emails": "Joe@gmail.com"}})


> Db.blog.findOne ()


{


"_id": ObjectId ("4fd2e468b2ac404941134bed"),


"Emails": [


"Joe@gmail.com",


"Joe@hotmail.com",


"Joe@gmail.com"


],


"username": "Joe"


}


--In an array, the subscript for the first element is 0, and then grows sequentially. The following example is to label the array as 1


--the element value of the second element is modified to the new value.


> db.blog.update ({"username": "Joe"}, {"$set": {"emails.1": "Joe@example.com"}})


> Db.blog.findOne ()


{


"_id": ObjectId ("4fd2e468b2ac404941134bed"),


"Emails": [


"Joe@gmail.com",


"Joe@example.com",


"Joe@gmail.com"


],


"username": "Joe"


}


Sometimes, especially when we modify the query result, we can't get the index of the result document array, MongoDB


--Provides a $ locator indicating the subscript for the query result. But he only updates the first matching element.


> db.blog.update ({"Emails": "joe@gmail.com"},{"$set": {"emails.$": "Joe@hotmail.com"}})


> Db.blog.findOne ()


{


"_id": ObjectId ("4fd2e468b2ac404941134bed"),


"Emails": [


"Joe@hotmail.com",


"Joe@example.com",


"Joe@gmail.com"


],


"username": "Joe"


}





6. Upsert:

Upsert is a special kind of update. If no document meets the update criteria, a new document is created based on this condition and the update document. If a matching document is found, the update is normal.

Copy Code code as follows:

> Db.blog.remove ()
> db.blog.update ({"username": "Joe"},{"username": "Joe", "Age": 30},true)
> Db.blog.findOne ()
{
"_id": ObjectId ("4fd2faac576cd9c101ac0f3d"),
"username": "Joe",
"Age": 30
}



The following example can modify the new value as it is added.


Copy Code code as follows:

> Db.blog.remove ()
> db.blog.update ({"Count": 25},{"$inc": {"Count": 3}},true)
> Db.blog.find ()
{"_id": ObjectId ("4fd2fd59576cd9c101ac0f3e"), "Count": 28}



Save is a shell function that can be inserted when a document is not present and updated when it exists. Upsert can also do the same work, but not as convenient as the Save command.


Copy Code code as follows:

> var x = Db.blog.findOne ()
> X.count = 40
40
> Db.blog.save (x)
> Db.blog.findOne ()
{"_id": ObjectId ("4fd2fde4576cd9c101ac0f3f"), "Count": 40}



7. Return updated Document:

You can obtain the number of documents that are updated when you update multiple documents by using the GetLastError command.

Copy Code code as follows:

> Db.blog.remove ()
> Db.blog.insert ({"Name": "Stephen"})
> Db.blog.insert ({"Name": "Stephen3"})
> Db.blog.insert ({"Name": "Stephen4"})
> db.blog.update ({},{"$set": {"name": "Liu"}},false,true)
--n:3 says the number of revisions is 3.
> Db.runcommand ({getlasterror:1})
{
"Updatedexisting": true,
"N": 3,
"ConnectionID": 1,
' err ': null,
"OK": 1
}



Findandmodify can be used to modify the results of the query atomically, or to delete the query results atomically.


Copy Code code as follows:



> Db.blog.insert ({"Name": "Stephen"})


> Db.blog.insert ({"Name": "Stephen2"})


> Db.blog.find ()


{"_id": ObjectId ("4fd30cd117f6dccb7c058244"), "name": "Stephen"}


{"_id": ObjectId ("4fd30cd417f6dccb7c058245"), "name": "Stephen2"}


> Db.runcommand ({"findandmodify": "blog", "Query": {"name": "Stephen2"}, "Update": {"$set": {"name": "Stephen3"}})


> Db.blog.find ()


{"_id": ObjectId ("4fd30cd117f6dccb7c058244"), "name": "Stephen"}


{"_id": ObjectId ("4fd30cd417f6dccb7c058245"), "name": "Stephen3"}


> RunCommand ({"findandmodify": "blog", "Query": {"name": "Stephen3"}, "Remove": true})


> Db.blog.find ()


{"_id": ObjectId ("4fd30cd117f6dccb7c058244"), "name": "Stephen"}





The values for each key in the Findandmodify command are as follows:


Findandmodify: The collection name of the string type.


Query: Queries the document to retrieve the criteria for the document.


Sort: The condition of the sorted result.


Update: Modifies the document to perform updates to the found document.


Remove: Boolean type that indicates whether the document is deleted.


NEW: A Boolean type that indicates whether to return the document before the update or the updated document. The default is before updating the document.


Update and remove must have a presence, and only one exists. If there are no matching documents, the command returns an error. This command has some limitations, that is, you can only work with one document at a time, you cannot perform upsert operations, you can only update existing documents.

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.