Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

03.Mongodb creates, updates, and deletes documents.

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)06/01 Report--

Insert:

> db.collectionName.insert ({"bar": "baz")}

Bulk insert:

If you want to insert multiple documents into the collection, it is faster to use bulk insert.

The batchInsert function implements bulk insertion, which takes an array of documents as an argument.

> db.collectionName.batchInsert ([{"_ id:0}, {" _ id ": 1}, {" _ id ": 2}])

> db.collectionName.find ()

{"_ id:0}

{"_ id": 1}

{"_ id": 2}

Delete the document:

> db.collectionName.remove ({})

The above command deletes only the documents in the collection, not the collection itself, nor does it delete the meta-information of the collection.

The remove function can accept a query document as a qualification as an optional parameter. Documents that meet the criteria will not be deleted until the parameters are given.

> db.collectionName.remove ({"xxxx": true})

Deleted data is permanent, cannot be undone, and cannot be restored.

Delete speed:

Deleting a document is usually quick, but if you want to empty the collection, it is faster to delete the collection directly using drop.

For example, insert test data:

> for (var item0; I)

< 1000000; i++) { ... db.tmps.insert({"foo":i}) ... } 使用remove删除,并记录花费时间: var timeRemoves = function() { var start = (new Date()).getTime(); db.tmps.remove({}); db.tmps.findOne();//Make sure the remove finishes before continuing var timeDiff = (new Date()).getTime() - start; print("Remove took:"+timeDiff+"ms"); } 更新文档: db.collection.update( , , { upsert: , multi: , writeConcern: } ) update有两个参数,一个是查询文档,用于定位需要更新的文档,另一个是修改器(modifier)文档,用于说明要对找到的文档进行哪些修改。 更新操作是不可分割的:若是两个更新同时发生,先到达服务器的先执行,接着执行令一个。 ·文档替换: 最简单的更新就是用一个新文档完全替换匹配的文档。这适用于进行大规模式迁移的情况。 例: 默认文档结构: >

Db.tmps.findOne ()

{

"_ id": ObjectId ("54f125773d3fab4bb9d6dc63")

"Name": "joe"

"Friends": 32

"Enemies": 2

Date: ISODate ("2015-02-28T02:18:21.858Z")

}

Write an definetmps.js document with the following content:

Var replaceupdate = function () {

Db.tmps.findOne ()

Var joe = db.tmps.findOne ({"Name": "joe"})

Joe.relationships = {"Friends": joe.Friends, "Enemies": joe.Enemies}

Joe.Username = joe.Name

Delete joe.Friends

Delete joe.Enemies

Delete joe.Name

Db.tmps.update ({"Name": "joe"}, joe)

Db.tmps.findOne ()

}

Then load it in Shell, execute the function replaceupdate (), and finally verify the document structure:

> load ("definetmps.js")

True

> replaceupdate ()

> db.tmps.findOne ()

{

"_ id": ObjectId ("54f125773d3fab4bb9d6dc63")

Date: ISODate ("2015-02-28T02:18:21.858Z")

"relationships": {

"Friends": 32

"Enemies": 2

}

"Username": "joe"

}

A common mistake is that the query criteria are matched to multiple documents, and then the update results in a duplicate "_ id" value due to the presence of the second parameter. The database throws an error and no document is updated.

Use modifiers:

Usually only part of the document needs to be updated. You can use atomic update modifiers to specify that certain fields in the document are updated.

1. Getting started with the "$set" modifier:

"$set" is used to specify the value of a field. If this field does not exist, create it. This is very convenient for updating the schema or adding user-defined keys.

For example, a document that stores user data is structured as follows

> db.tmps.findOne ()

{

"_ id": ObjectId ("54f131d0f755cba4f8d7cb2a")

"name": "joe"

"age": 32

"sex": "male"

"location": "Wisconsin"

}

To add a new key to the user's favorite book, you can use "$set":

> db.tmps.update ({"_ id": ObjectId ("54f131d0f755cba4f8d7cb2a")}

... {"$set": {"favorite book": "war and peace"}})

Then we have a new key in the document:

> db.tmps.findOne ()

{

"_ id": ObjectId ("54f131d0f755cba4f8d7cb2a")

"name": "joe"

"age": 32

"sex": "male"

"location": "Wisconsin"

"favorite book": "war and peace"

}

At this time, the button that likes books already exists. If you want to change one, you can update it directly through $set.

You can even change the type of key with "$set". For example, if users like a lot of books, they can change the "favorite book" key into an array:

> db.tmps.update ({"_ id": ObjectId ("54f131d0f755cba4f8d7cb2a")}

. {"$set": {"favorite book": ["book1", "book2", "book3"]}})

If the user doesn't like reading, you can delete the key value completely with "$unset".

> db.tmps.update ({"_ id": ObjectId ("54f131d0f755cba4f8d7cb2a")}

. {"$unset": {"favorite book": 1}})

You can also modify embedded documents with "$set":

> db.tmps.findOne ()

{

"_ id": ObjectId ("54f131d0f755cba4f8d7cb2a")

"name": "joe"

"age": 32

"sex": "male"

"location": "Wisconsin"

"contact": {

"email": "123@qq.com"

"pnum": "13212342112"

}

}

> db.tmps.update ({"name": "joe"}

... {"$set": {"contact.email": "1450327195@qq.com"}})

> db.tmps.findOne ()

{

"_ id": ObjectId ("54f131d0f755cba4f8d7cb2a")

"name": "joe"

"age": 32

"sex": "male"

"location": "Wisconsin"

"contact": {

"email": "1450327195@qq.com"

"pnum": "13212342112"

}

}

two。 Increase and decrease "$inc"

The "$inc" modifier is used to increase the value of an existing key, and if the key does not exist, one will be created.

"$inc" is similar to "$set" in that it is designed to increase and decrease numbers. "$inc" can only be used for values of × ×, length × ×, or double-precision floating-point values.

> db.tmps.update ({"name": "joe"}

. {"$inc": {"age": 1}})

> db.tmps.findOne ()

{

"_ id": ObjectId ("54f131d0f755cba4f8d7cb2a")

"name": "joe"

"age": 33

"sex": "male"

"location": "Wisconsin"

"contact": {

"email": "1450327195@qq.com"

"pnum": "13212342112"

}

}

3. Array modifier

There is a large class of important modifiers available for manipulating arrays. Arrays are commonly used and very useful data structures: not only are they lists that can be referenced by indexes, but they can also be used as set.

4. Add element "$push"

If the array already exists, "$push" adds an element to the end of the existing array, or creates a new array without it.

Such as:

> db.tmps.update ({"name": "joe"}

. {"$push": {"comments": {"name": "bob", "email": "bob@qq.com"}})

It is also added to continue to use "$push", which is a relatively simple form of "$push", which can also be applied to some of the more complex array operations.

Using the "$each" sub-operator, you can add multiple values in a single "$push" operation.

Db.tmps.update ({"name": "joe"}

. {"$push": {"comments": {"$each": [{"name": "bob", "email": "bob@qq.com"}, {"name": "carlo", "email": "carlo@qq.com"})

PS: through the implementation of "$set":

> db.tmps.update ({"name": "joe"}

. {"$set": {"comments": [{"name": "bob", "email": "bob@qq.com"}, {"name": "carlo", "email": "carlo@qq.com"}]}})

If you want the maximum length of the array to be fixed, you can use "$slice" and "$push" together to ensure that the array does not exceed the set maximum length, which in effect results in an array of up to N elements.

> db.tmps.update ({"name": "joe"}

... {"$push": {"favoritetop": {

... "$each": [{"name": "book", "level": 3}

... {"name": "music", "level": 1}

... {"name": "movie", "level": 4}

... {"name": "run", "level": 2}]

... "$slice":-3

... "$sort": {"level":-1})

Note: you cannot just use "slice" or "$sort" with "$push", and you must use "$each".

5. Using an array as a dataset

If you use an array as a dataset, make sure that the array elements are not duplicated. This can be done with "$ne" in the query document.

(test) > db.tmps.findOne ()

{

"_ id": ObjectId ("54f131d0f755cba4f8d7cb2a")

"name": "joe"

"age": 43

"emails": [

"aa@qq.com"

"bb@qq.com"

"cc@qq.com"

]

}

> db.tmps.update ({"emails": {"$ne": "aa@qq.com"}}, {"$push": {"emails": "aa@qq.com"}})

WriteResult ({"nMatched": 0, "nUpserted": 0, "nModified": 0})

> db.tmps.update ({"emails": {"$ne": "dd@qq.com"}}, {"$push": {"emails": "a@qq.com"}})

WriteResult ({"nMatched": 1, "nUpserted": 0, "nModified": 1})

As you can see here, $ne is judged in the query, and the subsequent $push operation is performed if the content does not exist.

You can also use "$addToSet" to do this:

> db.tmps.findOne ()

{

"_ id": ObjectId ("54f131d0f755cba4f8d7cb2a")

"name": "joe"

"age": 43

"emails": [

"aa@qq.com"

"bb@qq.com"

"cc@qq.com"

]

}

> db.tmps.update ({"name": "joe"}

... {"$addToSet": {"emails": "aa@qq.com"}})

WriteResult ({"nMatched": 1, "nUpserted": 0, "nModified": 0})

> db.tmps.update ({"name": "joe"}

... {"$addToSet": {"emails": "dd@qq.com"}})

WriteResult ({"nMatched": 1, "nUpserted": 0, "nModified": 1})

(test) > db.tmps.findOne ()

{

"_ id": ObjectId ("54f131d0f755cba4f8d7cb2a")

"name": "joe"

"age": 43

"emails": [

"aa@qq.com"

"bb@qq.com"

"cc@qq.com"

"dd@qq.com"

]

}

Combining "$addToSet" and "$each" can add several different values, which cannot be achieved with the combination of "$ne" and "$push".

> db.tmps.update ({"name": "joe"}

... {"$addToSet": {"emails": {"$each": [

... "a@qq.com", "b@qq.com", "c@qq.com", "d@qq.com"]}

6. Delete element

There are several ways to remove elements from an array. If you think of an array as a queue or stack, you can use the "$pop" modifier to remove elements from either end of the array.

> db.tmps.update ({"name": "joe"}

. {"$pop": {"emails": 1}}) / / removes the element from the end of the array.

> db.tmps.update ({"name": "joe"}, {"$pop": {"emails":-1}}) / / removes elements from the beginning of the array.

Sometimes you need to delete an element based on specific conditions, not just based on the location of the element, where you can use "$pull". It deletes all matching documents, not just one. Execute pull 1 on the array [1, 1, 2, 1], and the result is an array of only one element [2].

7. Position-based array modifier

By location or positioning operator ("$"):

Array subscripts start with 0, and you can select elements by using the subscript directly as a build.

> db.tmps.findOne ()

{

"_ id": ObjectId ("54f131d0f755cba4f8d7cb2a")

"name": "joe"

"age": 43

"emails": [

"bb@qq.com"

"cc@qq.com"

"dd@qq.com"

"a@qq.com"

"b@qq.com"

"c@qq.com"

]

}

> db.tmps.update ({"name": "joe"}

... {"$set": {"emails.3": "aa@qq.com"}})

WriteResult ({"nMatched": 1, "nUpserted": 0, "nModified": 1})

> db.tmps.findOne ()

{

"_ id": ObjectId ("54f131d0f755cba4f8d7cb2a")

"name": "joe"

"age": 43

"emails": [

"bb@qq.com"

"cc@qq.com"

"dd@qq.com"

"aa@qq.com"

"b@qq.com"

"c@qq.com"

]

}

In many cases, you can't know to change the subscript of an array without querying the document beforehand. To solve this problem, Mongodb provides the location operator "$" to locate and update the array elements that the query has matched. As follows:

> db.blog.findOne ()

{

"_ id": ObjectId ("54f56483d9c146390ce21c58")

"title": "my frist blog."

"content": "a b c d e f g."

"comments": [

{

"comment": "good"

"author": "joe"

"votes": 0

}

{

"comment": "it's ok"

"author": "john"

"votes": 2

}

]

}

> db.blog.update ({"comments.author": "joe"}

... {"$set": {"comments.$.author": "jim"}})

WriteResult ({"nMatched": 1, "nUpserted": 0, "nModified": 1})

> db.blog.findOne ()

{

"_ id": ObjectId ("54f56483d9c146390ce21c58")

"title": "my frist blog."

"content": "a b c d e f g."

"comments": [

{

"comment": "good"

"author": "jim"

"votes": 0

}

{

"comment": "it's ok"

"author": "john"

"votes": 2

}

]

}

Note that the locator updates only the first matching element.

Special update: upsert

Upsert update, if no document is found that meets the update criteria, a new document will be created based on this condition and the updated document. If a matching document is found, it is updated normally.

The third parameter of the update operation is true, then the upsert update!

Db.test.update ({"url": "www.example.com"}, {"$inc": {"pageviews": 1}}, true) / / this is abbreviated.

Db.test.update ({"url": "www.example.com"}, {"$inc": {"pageviews": 1}}, {upsert:true})

Save function:

When you use the save function, it automatically creates a document if it doesn't exist; if it does, it updates it. It has only one parameter: document. If the document has a "_ id" key, save will call upsert; otherwise call insert.

> db.tmps.findOne ()

{

"_ id": ObjectId ("54f131d0f755cba4f8d7cb2a")

"name": "joe"

"age": 43

"emails": [

"bb@qq.com"

"cc@qq.com"

"dd@qq.com"

"aa@qq.com"

"b@qq.com"

"c@qq.com"

]

}

> var x = db.tmps.findOne ()

(test) > x.age = 23

twenty-three

> db.tmps.save (x)

WriteResult ({"nMatched": 1, "nUpserted": 0, "nModified": 1})

> db.tmps.findOne ()

{

"_ id": ObjectId ("54f131d0f755cba4f8d7cb2a")

"name": "joe"

"age": 23

"emails": [

"bb@qq.com"

"cc@qq.com"

"dd@qq.com"

"aa@qq.com"

"b@qq.com"

"c@qq.com"

]

}

Update multiple documents:

By default, updates perform actions only on the first document that matches the criteria. To update all matches, you can set the fourth parameter of update to true.

> db.tmps.find ()

{"_ id": ObjectId ("54f131d0f755cba4f8d7cb2a"), "name": "joe", "age": 23}

{"_ id": ObjectId ("54f6aa46d9c146390ce21c5f"), "name": "peter", "age": 23}

{"_ id": ObjectId ("54f6aa4cd9c146390ce21c60"), "name": "carlo", "age": 23}

> db.tmps.update ({"age": 23}, {"$set": {"age": 24}}, false,true) / / shorthand method

> db.tmps.update ({"age": 23}, {"$set": {"age": 24}}, {upsert:false,multi:true})

> db.tmps.find ()

{"_ id": ObjectId ("54f131d0f755cba4f8d7cb2a"), "name": "joe", "age": 24}

{"_ id": ObjectId ("54f6aa46d9c146390ce21c5f"), "name": "peter", "age": 24}

{"_ id": ObjectId ("54f6aa4cd9c146390ce21c60"), "name": "carlo", "age": 24}

Write security mechanism (write concern)

Is a client setting that controls the security level of writes.

PS: the content is organized in the authoritative Guide to Mongodb

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report