mongoDB学习(二)之常用的修改操作
插入文档(插入数据库) 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 }

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

This article introduces how to configure MongoDB on Debian system to achieve automatic expansion. The main steps include setting up the MongoDB replica set and disk space monitoring. 1. MongoDB installation First, make sure that MongoDB is installed on the Debian system. Install using the following command: sudoaptupdatesudoaptinstall-ymongodb-org 2. Configuring MongoDB replica set MongoDB replica set ensures high availability and data redundancy, which is the basis for achieving automatic capacity expansion. Start MongoDB service: sudosystemctlstartmongodsudosys

This article describes how to build a highly available MongoDB database on a Debian system. We will explore multiple ways to ensure data security and services continue to operate. Key strategy: ReplicaSet: ReplicaSet: Use replicasets to achieve data redundancy and automatic failover. When a master node fails, the replica set will automatically elect a new master node to ensure the continuous availability of the service. Data backup and recovery: Regularly use the mongodump command to backup the database and formulate effective recovery strategies to deal with the risk of data loss. Monitoring and Alarms: Deploy monitoring tools (such as Prometheus, Grafana) to monitor the running status of MongoDB in real time, and

When developing an e-commerce website, I encountered a difficult problem: how to provide users with personalized product recommendations. Initially, I tried some simple recommendation algorithms, but the results were not ideal, and user satisfaction was also affected. In order to improve the accuracy and efficiency of the recommendation system, I decided to adopt a more professional solution. Finally, I installed andres-montanez/recommendations-bundle through Composer, which not only solved my problem, but also greatly improved the performance of the recommendation system. You can learn composer through the following address:

It is impossible to view MongoDB password directly through Navicat because it is stored as hash values. How to retrieve lost passwords: 1. Reset passwords; 2. Check configuration files (may contain hash values); 3. Check codes (may hardcode passwords).

Detailed explanation of MongoDB efficient backup strategy under CentOS system This article will introduce in detail the various strategies for implementing MongoDB backup on CentOS system to ensure data security and business continuity. We will cover manual backups, timed backups, automated script backups, and backup methods in Docker container environments, and provide best practices for backup file management. Manual backup: Use the mongodump command to perform manual full backup, for example: mongodump-hlocalhost:27017-u username-p password-d database name-o/backup directory This command will export the data and metadata of the specified database to the specified backup directory.

Encrypting MongoDB database on a Debian system requires following the following steps: Step 1: Install MongoDB First, make sure your Debian system has MongoDB installed. If not, please refer to the official MongoDB document for installation: https://docs.mongodb.com/manual/tutorial/install-mongodb-on-debian/Step 2: Generate the encryption key file Create a file containing the encryption key and set the correct permissions: ddif=/dev/urandomof=/etc/mongodb-keyfilebs=512

MongoDB and relational database: In-depth comparison This article will explore in-depth the differences between NoSQL database MongoDB and traditional relational databases (such as MySQL and SQLServer). Relational databases use table structures of rows and columns to organize data, while MongoDB uses flexible document-oriented models to better suit the needs of modern applications. Mainly differentiates data structures: Relational databases use predefined schema tables to store data, and relationships between tables are established through primary keys and foreign keys; MongoDB uses JSON-like BSON documents to store them in a collection, and each document structure can be independently changed to achieve pattern-free design. Architectural design: Relational databases need to pre-defined fixed schema; MongoDB supports

The main tools for connecting to MongoDB are: 1. MongoDB Shell, suitable for quickly viewing data and performing simple operations; 2. Programming language drivers (such as PyMongo, MongoDB Java Driver, MongoDB Node.js Driver), suitable for application development, but you need to master the usage methods; 3. GUI tools (such as Robo 3T, Compass) provide a graphical interface for beginners and quick data viewing. When selecting tools, you need to consider application scenarios and technology stacks, and pay attention to connection string configuration, permission management and performance optimization, such as using connection pools and indexes.
