Home Database Mysql Tutorial mongoDB学习(二)之常用的修改操作

mongoDB学习(二)之常用的修改操作

Jun 07, 2016 pm 04:02 PM
mongodb Revise study insert operate number document use

插入文档(插入数据库) db.person.insert({_id:0001,nameyuexin}) 清除数据 db.person.drop() 批量插入文档 shell中不支持批量插入 完成批量插入使用for循环 for(var i=0;i10;i++){ .. db.persons.insert({_id:i,name:yuexin+i}) .. } save操作 save操作与in

插入文档(插入数据库)
db.person.insert({_id:"0001",name"yuexin"})
清除数据
db.person.drop()
批量插入文档
shell中不支持批量插入
完成批量插入使用for循环
for(var i=0;i .. db.persons.insert({_id:i,name:"yuexin"+i})
.. }

save操作
save操作与insert操作的区别是当id一样的时候save会变成更新操作而insert会报错


删除列表中所有数据
db.persons.remove()删除persons中的数据但是不删除索引(db.system.indexes.find()中有值)
对于
db.person.drop()会删除索引
删除带查询条件的
db.persons.remove({_id:"3"})

如果想清除一个数据量十分庞大的集合,直接删除该集合并且重新建立索引的办法要比直接用remove的效率高很多。

1.强硬的文档替换式更新操作
update更新
> db.persons.update({age:55},{name:"000"})
2.主键冲突时时候会报错并且停止更新操作
因为是强硬替换的文档和已有文档id冲突时时候会报错
3.insertOrUpdate操作
目的:查询器查询出来数据就执行更新操作,查不出来就替换操作
做法:> db.persons.update({name:"0004"},{name:"1114"},true)
4.批量更新
> db.persons.update({name:"yuexin"},{$set:{name:"text"}},false,true)
默认情况当查询器查出多条数据的时候默认就修改第一条数据。
db.[documentName].update({查询器},{修改器},false,true)

修改器:
$set 用来指定一个键值对,如果存在就进行修改,不存在就进行添加
$inc 只是使用于数字类型,他可以为指定的键对应的数字类型的数值做加减操作。
> db.persons.update({age:20},{$inc:{age:-2}})
$unset 删除指定的键
> db.persons.update({age:18},{$unset:{age:1}})
$push
1.如果指定的键是数组追加新的数值
> db.persons.insert({_id:0,name:0,book:[]})
> db.persons.find()
{ "_id" : 0, "name" : 0, "book" : [ ] }
> db.persons.update({name:0},{$push:{book:"abc"}})
> db.persons.find()
{ "_id" : 0, "book" : [ "abc" ], "name" : 0 }
> db.persons.update({name:0},{$push:{book:"abcd"}})
> db.persons.update({name:0},{$push:{book:"abcd"}})
> db.persons.find()
{ "_id" : 0, "book" : [ "abc", "abcd", "abcd" ], "name" : 0 }
2.如果指定的键不是数组,则中断当前操作
Cannot apply $push/$pushAll modifier to non-array
3.如果不存在指定的键则创建数组类型的键值对
> db.persons.update({name:0},{$push:{things:"abcd"}})
> db.persons.find()
{ "_id" : 0, "book" : [ "abc", "abcd", "abcd" ], "name" : 0, "things" : [ "abcd"
] }

$pushAll 与push相似,是批量加入数组数据
> db.persons.update({name:0},{$pushAll:{things:["abcd","01","02"]}})
> db.persons.find()
{ "_id" : 0, "book" : [ "abc", "abcd", "abcd" ], "name" : 0, "things" : [ "abcd"
, "abcd", "01", "02" ] }

$addToSet 目标数组存在此项则不操作,不存在此项则加进去
> db.persons.insert({_id:0,name:0,book:[]})
> db.persons.update({name:0},{$addToSet:{book:"abcd"}})
> db.persons.find()
{ "_id" : 0, "book" : [ "abcd" ], "name" : 0 }
> db.persons.update({name:0},{$addToSet:{book:"abcd"}})
> db.persons.find()
{ "_id" : 0, "book" : [ "abcd" ], "name" : 0 }

$pop 删除第一个或者最后一个(-1为第一个,1为最后一个)
> db.persons.update({name:0},{$pop:{book:-1}})

$pull 删除指定的一个
> db.persons.update({name:0},{$pull:{book:"01"}})

$pull 删除多个
> db.persons.update({name:0},{$pullAll:{book:["01","02"]}})

$ 数组定位器,如果数组有多个数值我们只想对其中一部分进行操作我们就要用到定位器($)(??)

修改器是放在最外面的,查询器是放在内层的

$addToSet与$each结合完成批量数组更新
有的话就不添加了
> db.persons.find()
{ "_id" : 0, "book" : [ "js" ], "name" : 0 }
> db.persons.update({_id:0},{$addToSet:{book:{$each:["js","db"]}}})
> db.persons.find()
{ "_id" : 0, "book" : [ "js", "db" ], "name" : 0 }

当document被创建的时候mongoDB为其分配内存和预留内存,当修改操作不超过预留内存的时候速度非常快,反而超过了就要分配新的内存则会消耗时间

runCommand可以执行mongoDB中的特殊函数
findAndModify就是特殊函数之一他的用于是返回update或remove后的文档
> db.persons.find()
{ "_id" : 0, "book" : [ "js", "db" ], "name" : 0 }
> ps = db.runCommand({
... "findAndModify":"persons",
... "query":{name:0},
... "update":{$set:{age:100}},
... new:true})
{
"lastErrorObject" : {
"updatedExisting" : true,
"n" : 1,
"connectionId" : 1,
"err" : null,
"ok" : 1
},
"value" : {
"_id" : 0,
"age" : 100,
"book" : [
"js",
"db"
],
"name" : 0
},
"ok" : 1
}
> ps.value
{ "_id" : 0, "age" : 100, "book" : [ "js", "db" ], "name" : 0 }
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

The difference between nodejs and vuejs The difference between nodejs and vuejs Apr 21, 2024 am 04:17 AM

Node.js is a server-side JavaScript runtime, while Vue.js is a client-side JavaScript framework for creating interactive user interfaces. Node.js is used for server-side development, such as back-end service API development and data processing, while Vue.js is used for client-side development, such as single-page applications and responsive user interfaces.

Nodejs front-end and back-end distinction Nodejs front-end and back-end distinction Apr 21, 2024 am 03:43 AM

Node.js can be used for both front-end (handling user interface and interactions) and back-end (managing logic and data). The front-end uses HTML, CSS, and JavaScript frameworks, while the front-end uses Node.js framework, database, and cloud services. The focus is different (the front-end focuses on experience, the back-end focuses on functionality), the running environment is different (the front-end is in the browser, the back-end is on the server), and the tools are different (the front-end and back-end use different code compilation and packaging tool sets), although both use JavaScript , but with access to different APIs and libraries.

How to view Golang function documentation in the IDE? How to view Golang function documentation in the IDE? Apr 18, 2024 pm 03:06 PM

View Go function documentation using the IDE: Hover the cursor over the function name. Press the hotkey (GoLand: Ctrl+Q; VSCode: After installing GoExtensionPack, F1 and select "Go:ShowDocumentation").

What to do if navicat expires What to do if navicat expires Apr 23, 2024 pm 12:12 PM

Solutions to resolve Navicat expiration issues include: renew the license; uninstall and reinstall; disable automatic updates; use Navicat Premium Essentials free version; contact Navicat customer support.

Is it difficult to learn nodejs on the front end? Is it difficult to learn nodejs on the front end? Apr 21, 2024 am 04:57 AM

For front-end developers, the difficulty of learning Node.js depends on their JavaScript foundation, server-side programming experience, command line familiarity, and learning style. The learning curve includes entry-level and advanced-level modules focusing on fundamental concepts, server-side architecture, database integration, and asynchronous programming. Overall, learning Node.js is not difficult for developers who have a solid foundation in JavaScript and are willing to invest the time and effort, but for those who lack relevant experience, there may be certain challenges to overcome.

Top 10 Global Digital Virtual Currency Trading Platform Ranking (2025 Authoritative Ranking) Top 10 Global Digital Virtual Currency Trading Platform Ranking (2025 Authoritative Ranking) Mar 06, 2025 pm 04:36 PM

In 2025, global digital virtual currency trading platforms are fiercely competitive. This article authoritatively releases the top ten digital virtual currency trading platforms in the world in 2025 based on indicators such as transaction volume, security, and user experience. OKX ranks first with its strong technical strength and global operation strategy, and Binance follows closely with high liquidity and low fees. Platforms such as Gate.io, Coinbase, and Kraken are at the forefront with their respective advantages. The list covers trading platforms such as Huobi, KuCoin, Bitfinex, Crypto.com and Gemini, each with its own characteristics, but investment should be cautious. To choose a platform, you need to consider factors such as security, liquidity, fees, user experience, currency selection and regulatory compliance, and invest rationally

Astar staking principle, income dismantling, airdrop projects and strategies & operation nanny-level strategy Astar staking principle, income dismantling, airdrop projects and strategies & operation nanny-level strategy Jun 25, 2024 pm 07:09 PM

Table of Contents Astar Dapp Staking Principle Staking Revenue Dismantling of Potential Airdrop Projects: AlgemNeurolancheHealthreeAstar Degens DAOVeryLongSwap Staking Strategy & Operation "AstarDapp Staking" has been upgraded to the V3 version at the beginning of this year, and many adjustments have been made to the staking revenue rules. At present, the first staking cycle has ended, and the "voting" sub-cycle of the second staking cycle has just begun. To obtain the "extra reward" benefits, you need to grasp this critical stage (expected to last until June 26, with less than 5 days remaining). I will break down the Astar staking income in detail,

Use Golang functions to build message-driven architectures in distributed systems Use Golang functions to build message-driven architectures in distributed systems Apr 19, 2024 pm 01:33 PM

Building a message-driven architecture using Golang functions includes the following steps: creating an event source and generating events. Select a message queue for storing and forwarding events. Deploy a Go function as a subscriber to subscribe to and process events from the message queue.

See all articles