Examples of data manipulation in the MongoDB tutorial

  • 2020-05-12 06:24:19
  • OfStack

1. Batch insert:

Inserting multiple documents once in an array can be done in a single TCP request, avoiding the extra overhead of multiple requests. In terms of data transfer volume, bulk inserts contain only one header, while multiple single inserts encapsulate the header data each time the data is inserted. For data import, we can do this using mongoimport.

2. Database cleaning:


    > db.users.remove()
 

The above command will clear all data in the users collection, but it will not delete the collection itself and the associated indexes. The data delete operation is not recoverable, 1 denier of the physical delete. A more efficient way to clean up case is to directly delete the collection object itself and all its associated indexes, and then rebuild them in turn, such as:

    > db.one_collection.drop()
 


3. Data update:

If there are multiple documents matching the update conditions when the data is updated, MongoDB will only update the first query result in order to avoid the repetitive conflict of _id after the update, such as:


    > 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. Modifier:

Using a modifier to update data is atomic and efficient, unlike all document updates where the _id of the updated document does not change, full document updates modify the _id of the document, as well as the associated index.


 > db.blog.find()
    { "_id" : ObjectId("4fcd7e2820668578cc1097d7"), "name" : "stephen", "age" : 41 }
    { "_id" : ObjectId("4fcd81bb20668578cc1097d9"), "name" : "stephen", "age" : 38 }
    --$inc The modifier will match the condition of the document age Key atoms with 1 , by default only updates the first 1 A qualified 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 }
    -- Can be achieved by update The end of the function 1 To specify the update of all eligible documents, 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 directly modifies the content of the matched document, if the modified key exists, otherwise new.
    > db.blog.update({"name":"stephen"},{"$set":{"genda":"male"}})
    > db.blog.find()
    { "_id" : ObjectId("4fcd88b720668578cc1097da"), "age" : "35", "genda" : "male", "name" : "stephen" }
    --$unset Modified in accordance with $set The function is completely opposite, such as:
    > db.blog.update({"name":"stephen"},{"$unset":{"genda":"male"}})
    > db.blog.find()
    { "_id" : ObjectId("4fcd88b720668578cc1097da"), "age" : "35", "name" : "stephen" }
    -- Can be achieved by $set Modifier modifies nested subdocuments.
    > db.blog.find()
    { "_id" : ObjectId("4fcd8e0220668578cc1097db"), "title" : "A Blog Post", "author" : { "name" : "joe", "email" : "joe@ee.com" } }
    > 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:


    > db.blog.insert({"title":"one blog"})
    > db.blog.find()
    { "_id" : ObjectId("4fcd909520668578cc1097dc"), "title" : "one blog" }
    -- If the key it operates on does not exist, it creates a new key value of type array.
    > log.update({"title":"one blog"}, {"$push": {"comments":{"content":"hello"}}})
    > db.blog.findOne()
    {
         "_id" : ObjectId("4fcd909520668578cc1097dc"),
         "comments" : [
                 {
                         "content" : "hello"
                 }
         ],
         "title" : "one blog"
    }
    -- if $push The key value for the operation already exists and is of type array, and 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 in the array already exists, the command returns without doing anything, otherwise it 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"
    }
    --$addToSet and $each The combination of can insert the array into another 1 In an 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 Delete from the array 1 Element, such as the parameter is 1 To delete from the end of the array 1 Elements, if it is -1 , is deleted from the header.
    > 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 The 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 function demonstration of modifying characters later.
    > 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 the array, number one 1 The subscripts of the elements are 0 And then it goes up. The following example is to subscript an array as 1
    --( The first 2 An element ) The element value is changed 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're modifying the results of a query, we don't know the index of the resulting array of documents, MongoDB
    -- provides $ The locator represents the subscript of the query result. But he only updates the first 1 Two matching elements.
    > 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 update. If no document meets the update criteria, a new document is created based on this condition and the updated document. If a matching document is found, it is updated normally.


 > 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 newly added value at the same time as adding it.

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

save is an shell function that can be inserted when the document does not exist and updated when it does. upsert can do the same thing, but not as convenient as the save command.

    > 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 use the getLastError command to get the number of documents that are updated when multiple documents are updated.


    > 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 Represents the number of modifications as 3 .
    > db.runCommand({getLastError:1})
    {
        "updatedExisting" : true,
        "n" : 3,
        "connectionId" : 1,
        "err" : null,
        "ok" : 1
    }
 

findAndModify can atomically modify query results or atomically delete query results.

    > 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 corresponding values for each key in the findAndModify command are as follows:
findAndModify: the name of a collection of string types.
query: query the document to retrieve the conditions of the document.
sort: conditions for sorting results.
update: modify the document to perform an update on the document found.
remove: Boolean type that indicates whether to delete a document.
new: Boolean type that indicates whether the document is returned before or after the update. The default is a pre-update document.
One of update and remove must exist, and only one can exist. If there is no matching document, the command returns an error. This command has some limitations, namely, it can only process one document at a time, cannot perform upsert operation, and can only update existing documents.


Related articles: