search
HomeDatabaseMysql TutorialMongoDB命令使用示例

MongoDB命令使用示例

Jun 07, 2016 pm 04:28 PM
mmongodbone timeuseOrderbooksExampleillustrate

用图书的示例来说明一下mongodb命令的使用。 添加 插入一个图书文档: db.books.insert({name:深入学习MongoDB}); 然后,可以看一下是否插入成功了: db.books.find(); 打印的结果类似这样: { _id : ObjectId(4f8e8a8e7a919fd8a1a37e2d), name : 深入学习Mo

用图书的示例来说明一下mongodb命令的使用。

添加

插入一个图书文档:

db.books.insert({name:’深入学习MongoDB’});

然后,可以看一下是否插入成功了:

db.books.find();

打印的结果类似这样:

{ “_id” : ObjectId(“4f8e8a8e7a919fd8a1a37e2d”), “name” : “深入学习MongoDB” }

好了,现在不想要这条记录了,删除掉:

db.books.remove();

再次使用find(),就不会打印内容了。这里要注意,remove()将删除集合中所有文档。如何删除指定条件的文档,后面再说。

修改

再次创建一个图书文档:

db.books.insert({name:’钱的历史’,items:[]});

这里我增加了一个空数组,后面有用。

现在我要将图书名称(name)改为:深入学习MongoDB。

命令:

db.books.update({_id:ObjectId(“4f8e8a8e7a919fd8a1a37e2d”)},{name:’深入学习MongoDB’},false);

上述命令的缺点是,items属性没有了。如果只想修改图书的名称,而不影响文档的其他属性,可以这样:

db.books.update({_id:ObjectId(“4f8ea9a619bc948142e0dad5″)},{$set:{name:’Deep in MongoDB’}},false);

现在,我想往空数组里添加一些东西,比如,一个条目:

{_id:ObjectId, type:’chapter’,items:[]}

那么,命令如下:

?db.books.update({_id:ObjectId(’4f8ea9a619bc948142e0dad5′)},{$push:{items:{_id:new ObjectId(),type:’chapter’,items:[]}}},false);

看一下显示的结果:

{
“_id” : ObjectId(“4f8ea9a619bc948142e0dad5″),
“items” : [
{
"_id" : ObjectId("4f8eaf227a919fd8a1a37e2e"),
"type" : "chapter",
"items" : [ ]
}
],
“name” : “野外维生食物”
}

现在我们想在4f8eaf227a919fd8a1a37e2e的条目的数组中加入内容,怎么做呢?要用到push,它可以向指定的数组追加元素:

db.books.update({_id:ObjectId(’4f8ea9a619bc948142e0dad5′)},{$push:{items:{_id:new ObjectId(),type:’chapter’,items:[]}}},false);

现在我又发现追加的元素的type值错了,想改成section:

db.books.update({_id:ObjectId(“4f8ea9a619bc948142e0dad5″),’items._id’:ObjectId(“4f8ef10b7a919fd8a1a37e32″)},{$set:{‘items.$.type’:'section’}},false);

我是否能在items的元素的items数组中再追加元素呢?答案是肯定的:

db.books.update({_id:ObjectId(“4f8ea9a619bc948142e0dad5″),’items._id’:ObjectId(“4f8ef10b7a919fd8a1a37e32″)},{$push:{‘items.$.items’:{_id:new ObjectId(),type:’section’,items:[]}}},false);

追加后的结果类似这样:

{
“_id” : ObjectId(“4f8ea9a619bc948142e0dad5″),
“items” : [
{
"_id" : ObjectId("4f8ef10b7a919fd8a1a37e32"),
"items" : [
{
"_id" : ObjectId("4f8ef4d17a919fd8a1a37e33"),
"type" : "section",
"items" : [ ]
}
],
“type” : “chapter”
}
]
}

删除

如果文档添加了不该有的属性,想删除,比如:

db.books.update({_id:ObjectId(’4f8e8a8e7a919fd8a1a37e2d’)},{$push:{hello:’test1′}},false);

为文档增加了一个没用的属性,he l lo,这是个数组。

删除它:

db.books.update({_id:ObjectId(’4f8e8a8e7a919fd8a1a37e2d’)},{$unset:{hello:1}},false);

Statement
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
MySQL BLOB : are there any limits?MySQL BLOB : are there any limits?May 08, 2025 am 12:22 AM

MySQLBLOBshavelimits:TINYBLOB(255bytes),BLOB(65,535bytes),MEDIUMBLOB(16,777,215bytes),andLONGBLOB(4,294,967,295bytes).TouseBLOBseffectively:1)ConsiderperformanceimpactsandstorelargeBLOBsexternally;2)Managebackupsandreplicationcarefully;3)Usepathsinst

MySQL : What are the best tools to automate users creation?MySQL : What are the best tools to automate users creation?May 08, 2025 am 12:22 AM

The best tools and technologies for automating the creation of users in MySQL include: 1. MySQLWorkbench, suitable for small to medium-sized environments, easy to use but high resource consumption; 2. Ansible, suitable for multi-server environments, simple but steep learning curve; 3. Custom Python scripts, flexible but need to ensure script security; 4. Puppet and Chef, suitable for large-scale environments, complex but scalable. Scale, learning curve and integration needs should be considered when choosing.

MySQL: Can I search inside a blob?MySQL: Can I search inside a blob?May 08, 2025 am 12:20 AM

Yes,youcansearchinsideaBLOBinMySQLusingspecifictechniques.1)ConverttheBLOBtoaUTF-8stringwithCONVERTfunctionandsearchusingLIKE.2)ForcompressedBLOBs,useUNCOMPRESSbeforeconversion.3)Considerperformanceimpactsanddataencoding.4)Forcomplexdata,externalproc

MySQL String Data Types: A Comprehensive GuideMySQL String Data Types: A Comprehensive GuideMay 08, 2025 am 12:14 AM

MySQLoffersvariousstringdatatypes:1)CHARforfixed-lengthstrings,idealforconsistentlengthdatalikecountrycodes;2)VARCHARforvariable-lengthstrings,suitableforfieldslikenames;3)TEXTtypesforlargertext,goodforblogpostsbutcanimpactperformance;4)BINARYandVARB

Mastering MySQL BLOBs: A Step-by-Step TutorialMastering MySQL BLOBs: A Step-by-Step TutorialMay 08, 2025 am 12:01 AM

TomasterMySQLBLOBs,followthesesteps:1)ChoosetheappropriateBLOBtype(TINYBLOB,BLOB,MEDIUMBLOB,LONGBLOB)basedondatasize.2)InsertdatausingLOAD_FILEforefficiency.3)Storefilereferencesinsteadoffilestoimproveperformance.4)UseDUMPFILEtoretrieveandsaveBLOBsco

BLOB Data Type in MySQL: A Detailed Overview for DevelopersBLOB Data Type in MySQL: A Detailed Overview for DevelopersMay 07, 2025 pm 05:41 PM

BlobdatatypesinmysqlareusedforvoringLargebinarydatalikeImagesoraudio.1) Useblobtypes (tinyblobtolongblob) Basedondatasizeneeds. 2) Storeblobsin Perplate Petooptimize Performance.3) ConsidersxterNal Storage Forel Blob Romana DatabasesizerIndimprovebackupupe

How to Add Users to MySQL from the Command LineHow to Add Users to MySQL from the Command LineMay 07, 2025 pm 05:01 PM

ToadduserstoMySQLfromthecommandline,loginasroot,thenuseCREATEUSER'username'@'host'IDENTIFIEDBY'password';tocreateanewuser.GrantpermissionswithGRANTALLPRIVILEGESONdatabase.*TO'username'@'host';anduseFLUSHPRIVILEGES;toapplychanges.Alwaysusestrongpasswo

What Are the Different String Data Types in MySQL? A Detailed OverviewWhat Are the Different String Data Types in MySQL? A Detailed OverviewMay 07, 2025 pm 03:33 PM

MySQLofferseightstringdatatypes:CHAR,VARCHAR,BINARY,VARBINARY,BLOB,TEXT,ENUM,andSET.1)CHARisfixed-length,idealforconsistentdatalikecountrycodes.2)VARCHARisvariable-length,efficientforvaryingdatalikenames.3)BINARYandVARBINARYstorebinarydata,similartoC

See all articles

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

Video Face Swap

Video Face Swap

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

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.