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

[MongoDB] 01, MongoDB Foundation

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

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

I. Overview of MongoDB

1. Introduction to MogoDB

What is MongoDB?

MongoDB is written in C++ language and is an open source database system based on distributed file storage.

In the case of high load, adding more nodes can ensure server performance.

MongoDB aims to provide scalable, high-performance data storage solutions for WEB applications.

MongoDB stores the data as a document, and the data structure consists of key-value (key= > value) pairs. MongoDB documents are similar to JSON objects. Field values can contain other documents, arrays, and document arrays.

A document is equivalent to a row of data in an mysql database

In October 2007, MongoDB was developed by the 10gen team. It was launched for the first time in February 2009.

On May 23, 2012, the MongoDB2.1 Development Branch released! This version uses a new architecture and includes many enhancements.

Latest stable version: 3.4.2

2. Characteristics of MongoDB

Main features

MongoDB provides a document-oriented storage that is relatively simple and easy to operate.

You can set the index of any property in the MongoDB record (such as FirstName= "Sameer", Address= "8 Gandhi Road") to achieve faster sorting.

You can create data mirrors locally or on the network, which makes MongoDB more scalable.

If the load increases (more storage space and stronger processing power are needed), it can be distributed among other nodes in the computer network. This is called fragmentation. (automatic slicing)

Mongo supports a rich set of query expressions. Query instructions use tags in the form of JSON to easily query objects and arrays embedded in a document.

MongoDb uses the update () command to replace the completed document (data) or some specified data fields.

Map/reduce in Mongodb is mainly used for batch processing and aggregation of data.

Map and Reduce. The Map function calls emit (key,value) to traverse all the records in the collection, passing key and value to the Reduce function for processing.

The Map and Reduce functions are written in Javascript, and you can perform MapReduce operations through db.runCommand or mapreduce commands.

GridFS is a built-in feature in MongoDB that can be used to store a large number of small files. Built-in distributed file system

MongoDB allows scripts to be executed on the server. You can write a function in Javascript and execute it directly on the server, or you can store the definition of the function on the server and call it directly next time.

MongoDB supports a variety of programming languages, such as RUBY,PYTHON,JAVA,C++,PHP,C#.

MongoDB is easy to install.

Second, concept analysis

No matter what database we study, we should learn the basic concepts. The basic concepts in mongodb are documents, collections, and databases, which we will introduce one by one below. The following table will help you understand some of the concepts in Mongo more easily:

SQL terminology / concept MongoDB terminology / concept explanation / description databasedatabase database tablecollection database table / collection rowdocument data record row / document columnfield data field / domain indexindex index table joins

Table connection. MongoDB does not support primary keyprimary key primary key. MongoDB automatically sets the _ id field as the primary key.

Through the following example, we can also get a more intuitive understanding of some of the concepts in Mongo:

Document

A document is a key-value pair (i.e. BSON). MongoDB documents do not need to set the same fields, and the same fields do not need the same data type, which is very different from relational databases, which is also a very prominent feature of MongoDB.

An example of a simple document is as follows:

{"site": "www.runoob.com", "name": "Rookie tutorial"}

It is important to note that:

The key / value pairs in the document are ordered.

The values in the document can be not only strings enclosed in double quotes, but also several other data types (or even the entire embedded document).

MongoDB is type-and case-sensitive.

MongoDB documents cannot have duplicate keys.

The key of the document is a string. With a few exceptions, keys can use any UTF-8 character.

Document key naming convention:

The key cannot contain\ 0 (null characters). This character is used to indicate the end of the key.

. And $have special meaning and can only be used in specific circumstances.

The keys that begin with the underscore "_" are reserved (not strictly required).

Every document has a hidden _ id key, the field, which is equivalent to the primary key in mysql

Set

Collections are MongoDB document groups, similar to tables in RDBMS (Relational Database Management system: Relational Database Management System). The collection exists in the database, and the collection has no fixed structure, which means that you can insert different formats and types of data into the collection, but usually the data we insert into the collection will have certain relevance.

For example, we can insert documents with the following different data structures into the collection:

{"site": "www.baidu.com"} {"site": "www.google.com", "name": "Google"} {"site": "www.runoob.com", "name": "Rookie tutorial", "num": 5}

When the first document is inserted, the collection is created.

Legal collection name

The collection name cannot be an empty string''.

The collection name cannot contain the\ 0 character (empty character), which represents the end of the collection name.

The collection name cannot be "system." At the beginning, this is the prefix reserved for the system collection.

User-created collection names cannot contain reserved characters. Some drivers do support inclusion in the collection name because some system-generated collections contain this character. Never include $in your name unless you want to access a collection created by this system.

The following is an example:

Db.col.findOne () capped collections

A Capped collections is a fixed-size collection.

It has high performance and queue expiration (in the order in which it is inserted). It is somewhat similar to the concept of "RRD".

Capped collections is a high-performance automatic maintenance of the insertion order of objects. It is very suitable for similar logging functions different from the standard collection, you have to explicitly create a capped collection, specifying the size of a collection, in bytes. The data storage space value of collection is allocated in advance.

Note that the specified storage size contains the header information of the database.

Db.createCollection ("mycoll", {capped:true, size:100000})

In capped collection, you can add new objects.

Updates can be made, however, objects do not increase storage space. If increased, the update will fail.

Deletion of the database is not allowed. Use the drop () method to delete all rows of collection.

Note: after deletion, you must explicitly recreate the collection.

In a 32bit machine, the maximum capped collection storage is 1e9 (1X109) bytes.

Database

Multiple databases can be set up in a mongodb.

A single instance of MongoDB can hold multiple independent databases, each with its own collection and permissions, and different databases are placed in different files.

The "show dbs" command displays a list of all the data.

Execute the "db" command to display the current database object or collection.

Run the "use db_name" command to use a specified database.

The database is also identified by name. The database name can be any UTF-8 string that meets the following conditions.

Cannot be an empty string (").

Must not contain''(space),., $, /,\ and\ 0 (space symbol).

It should be all lowercase.

Up to 64 bytes.

Meta data

The information in the database is stored in the collection. They use the system's namespace:

Dbname.system.*

In the MongoDB database, the namespace .system. * is a special collection (Collection) that contains a variety of system information, as follows:

The collection namespace description dbname.system.namespaces lists all namespaces. Dbname.system.indexes lists all indexes. Dbname.system.profile contains database profile (profile) information. Dbname.system.users lists all users who can access the database. The dbname.local.sources contains the server information and status of the replication peer (slave).

There are the following restrictions on modifying objects in the system collection.

Insert data in `system`.`indexes` to create an index. But otherwise, the table information is immutable (the special drop index command will automatically update the relevant information).

`system`.`users` is modifiable. `system`.`profile` is removable.

MongoDB data type

The following table shows several data types commonly used in MongoDB.

The data type describes the String string. Data types commonly used to store data. In MongoDB, a string encoded by UTF-8 is legal. Integer integer value. Used to store numeric values. According to the server you use, it can be divided into 32-bit or 64-bit. Boolean Boolean value. Used to store Boolean values (true / false). Double double precision floating point value. Used to store floating-point values. Min/Max keys compares a value to the lowest and highest values of the BSON (binary JSON) element. Arrays is used to store an array or list or multiple values as a key. Timestamp timestamp. Record when the document was modified or added. Object is used to embed documents. Null is used to create null values. Symbol symbol. This data type is basically equivalent to a string type, but it is generally used in languages with special symbolic types. Date date time. Stores the current date or time in UNIX time format. You can specify your own date and time: create a Date object and pass in the year, month and day information. Object ID object ID. The ID used to create the document. Binary Data binary data. Used to store binary data. Code code type. Used to store JavaScript code in a document. Regular expression regular expression type. Used to store regular expressions.

II. MongoDB installation

Various versions of the MongoDB installation package are available on the MongoDB official website, including rpm package, general binary package, and source package.

1. Yum installation

If there is version 2.4.14 of MongoDB in the epel source, you can install it directly with yum.

[root@Node7 ~] # yum list | grep "^ mongodb" mongodb.x86_64 2.4.14-4.el6 epel mongodb-server.x86_64 2.4.14-4.el6 epel [root@Node7 ~] # yum install mongodb-server mongodb [root@Node7 ~] # rpm-ql mongodb-server/etc/logrotate.d/mongodb / etc/mongodb.conf/etc/rc.d/init.d/mongod/etc/sysconfig/mongod/usr/bin/mongod/usr/bin/mongos/usr/share/man/man1/mongod.1.gz/usr/share/man/man1/mongos.1.gz/var/lib/mongodb/var/log/mongodb/var/run/mongodb [root@Node7 ~] # rpm-ql mongodb/usr/bin/bsondump/usr/bin/mongo/usr/bin/mongodump/usr/bin/mongoexport/usr/ Bin/mongofiles/usr/bin/mongoimport/usr/bin/mongooplog/usr/bin/mongoperf/usr/bin/mongorestore/usr/bin/mongosniff/usr/bin/mongostat/usr/bin/mongotop/usr/share/man/man1/bsondump.1.gz

2. Start mongod

[root@Node7 ~] # service mongod reload

Mongodb does not enable authentication by default:

3. The use of client-side mongo

The usage of mongo:

[root@Node7 ~] # mongo-- helpMongoDB shell version: 2.4.14usage: mongo [options] [db address] [file names (ending in .js)] db address can be: foo foo database on local machine 192.169.0.5/foo foo database on 192.168.0.5 machine 192.169.0.5:9999/foo foo database on 192.168.0.5 machine on port 9999options:-- shell Run the shell after executing files-- nodb don't connect to mongod on startup-no'db address' arg Expected-- norc will not run the ".mongorc.js" file on start up-- quiet be less chatty-- port arg port to connect to-- host arg Server to connect to-- eval arg evaluate javascript-u [--username] arg username for authentication-p [--password] arg password for authentication-- authenticationDatabase arg user source (defaults to dbname)-- authenticationMechanism arg (= MONGODB-CR) authentication Mechanism-h [--help] show this usage information-- version show version information-- verbose increase verbosity-- ipv6 enable IPv6 support (disabled by Default)-ssl use SSL for all connections-sslCAFile arg Certificate Authority for SSL-sslPEMKeyFile arg PEM certificate/key file for SSL-sslPEMKeyPassword arg password for key in PEM file for SSL

Example:

[root@Node7 ~] # mongo-- host 192.168.10.7 MongoDB shell version: 2.4.14connecting to: 192.168.10.7:27017/test # connects to test database > help db.help () help on db methods # database-related commands db.mycoll.help () help on collection methods by default # collection-related commands sh.help () sharding helpers rs.help () replica set helpers help admin administrative help help connect connecting to a db help help keys key shortcuts help misc misc things To know help mr mapreduce show dbs show database names # shows the existing database show collections show collections in current database # shows the existing table show users Show users in current database show profile show most recent system.profile entries with time > = 1ms # performance probe tool show logs show the accessible logger names show log [name] prints out the last segment of log in memory 'global' is default use set current database db.foo.find () list objects in collection foo db.foo.find ({a: 1}) list objects in foo where a = = 1 it result of the last line evaluated Use to further iterate DBQuery.shellBatchSize = x set default number of items to display on shell exit quit the mongo shell > use mydb # mongodb is weird. You can use switched to db mydb > show dbs; # without creating a database. There is no mydb library. When a use library is created and tables are created in it, the library admin (empty) local 0.078125GBtest (empty) is automatically created.

Common commands:

Help

Db.help ()

Db.mycoll.help ()

Db.stats (): database status

Db.serverStatus (): mongodb database server status

Show dbs 、 show collections

Db.getCollectionNames (): displays a list of the names of all collections of the current data

III. Getting started with CRUD

CRUD refers to the acronym of adding (Create), reading query (Retrieve), Update (Update), and deleting (Delete) when doing calculation processing. It is mainly used to describe the basic operational functions of the database or persistence layer in the software system.

Mongo supports a rich set of query expressions. Query instructions use tags in the form of JSON to easily query objects and arrays embedded in a document.

JSON:JavaScript Object Notation

Lightweight XML

Json has two structures:

A collection of name / value objects

An ordered list of values

1. Insert the document

The data structure of the document is basically the same as JSON. All the data stored in the collection are in BSON format. BSON is a binary storage format similar to json, referred to as Binary JSON.

MongoDB uses insert () with the following syntax:

Db.COLLECTION_NAME.insert (document)

There is no need to create databases and collections first: the database is automatically delayed, and collections do not need to be defined, so you can insert data directly

[root@Node7 ~] # mongo-- host 192.168.10.7 MongoDB shell version: 2.4.14connecting to: 192.168.10.7:27017/test > show dbslocal 0.078125GB > use testdbswitched to db testdb > show dbslocal 0.078125GBtest (empty) testdb 0.203125GB > db.stats () {"db": "testdb", "collections": 0, "objects": 0, "avgObjSize": 0, "dataSize": 0 "storageSize": 0, "numExtents": 0, "indexes": 0, "indexSize": 0, "fileSize": 0, "nsSizeMB": 0, "dataFileVersion": {}, "ok": 1} > db.students.insert ({name: "tom") Age:23}) > show collectionsstudentssystem.indexes > db.stats () {"db": "testdb", "collections": 3, "objects": 5, "avgObjSize": 48, "dataSize": 240," storageSize ": 12288," numExtents ": 3," indexes ": 1," indexSize ": 8176 "fileSize": 201326592, "nsSizeMB": 16, "dataFileVersion": {"major": 4, "minor": 5}, "ok": 1} > db.students.stats () # shows the status of the specified collection {"ns": "testdb.students" # name "count": 1, "size": 56, "avgObjSize": 56, "storageSize": 4096, "numExtents": 1, "nindexes": 1, "lastExtentSize": 4096, "paddingFactor": 1, "systemFlags": 1, "userFlags": 0, "totalIndexSize": 8176 "indexSizes": {"_ id_": 8176}, "ok": 1} > db.getCollectionNames () ["students", "system.indexes"]

2. Query documents

The syntax format of MongoDB query data is as follows:

Db.COLLECTION_NAME.find ()

View help information for db.COLLECTION_NAME.find ():

> db.a.find (). Help () find () modifiers .sort ({...}) .limit (n) .skip (n) .count ()-total # of objects matching query, ignores skip,limit .size ()-total # of objects cursor would return, honors skip Limit. Explain ([verbose]) .hint (...) .addOption (n)-adds op_query options-- see wire protocol. _ addSpecial (name) Value)-http://dochub.mongodb.org/core/advancedqueries#AdvancedQueries-Metaqueryoperators .batchSize (n)-sets the number of docs to return per getMore .showDiskLoc ()-adds a $diskLoc field to each returned object .min (idxDoc) .max (idxDoc) Cursor methods .toArray ()-iterates through docs and returns an array of the results .forEach (func) .map (func) .hasNext () .next () .objsLeftInBatch ()-returns count of docs left in current batch (when exhausted A new getMore will be issued) .count (applySkipLimit)-runs command at server .itcount ()-iterates through documents and counts them

Find () is easy to use:

> db.students.find () # needs to be under the corresponding collection {"_ id": ObjectId ("58d50e6376002e9a38ccceec"), "name": "tom", "age": 23} > db.students.find (). Count () 1 > db.students.count () 1

In addition to the find () method, there is a findOne () method that returns only one document:

> db.students.findOne () # only returns the first one, and multiple execution does not bring down {"_ id": ObjectId ("58d50e6376002e9a38ccceec"), "name": "tom", "age": 23} > db.students.findOne () {"_ id": ObjectId ("58d50e6376002e9a38ccceec"), "name": "tom", "age": 23}.

Advanced usage of find ()

Comparison operation: $gt,$gte,$lt,$lte,$ne

The similar statement in the operation format example RDBMS is equal to {:} db.col.find ({"by": "Rookie tutorial"}) where by = "Rookie tutorial" less than {: {$lt:}} db.col.find ({"likes": {$lt:50}}) where likes

< 50小于或等于{:{$lte:}}db.col.find({"likes":{$lte:50}})where likes 50大于或等于{:{$gte:}}db.col.find({"likes":{$gte:50}})where likes >

= 50 is not equal to {: {$ne:}} db.col.find ({"likes": {$ne:50}}) where likes! = 50

Example:

> db.students.find () {"_ id": ObjectId ("58d50e6376002e9a38ccceec"), "name": "tom", "age": 23} {"_ id": ObjectId ("58d5183976002e9a38ccceed"), "name": "xj"} {"_ id": ObjectId ("58d51b2776002e9a38ccceee"), "name": "xx", "Age": 35} {"_ id": ObjectId ("58d51cec76002e9a38ccceef"), "name": "x1" "age": 40} {"_ id": ObjectId ("58d51cff76002e9a38cccef0"), "name": "x2", "age": 50} > db.students.find ({age: {$gt:30}}) # characters case-sensitive {"_ id": ObjectId ("58d51cec76002e9a38ccceef"), "name": "x1", "age": 40} {"_ id": ObjectId ("58d51cff76002e9a38cccef0"), "name": "x2" "age": 50} > db.students.find ({age: {$lt:40}}) {"_ id": ObjectId ("58d50e6376002e9a38ccceec"), "name": "tom", "age": 23} > db.students.find ({age: {$lte:40}}) {"_ id": ObjectId ("58d50e6376002e9a38ccceec"), "name": "tom", "age": 23} {"_ id": ObjectId ("58d51cec76002e9a38ccceef") "name": "x1", "age": 40}

$in finds the data listed in the specified list

$nin

Syntax format:

{filed: {$in: []}}

> db.students.find () {"_ id": ObjectId ("58d50e6376002e9a38ccceec"), "name": "tom", "age": 23} {"_ id": ObjectId ("58d5183976002e9a38ccceed"), "name": "xj"} {"_ id": ObjectId ("58d51b2776002e9a38ccceee"), "name": "xx", "Age": 35} {"_ id": ObjectId ("58d51cec76002e9a38ccceef"), "name": "x1" "age": 40} {"_ id": ObjectId ("58d51cff76002e9a38cccef0"), "name": "x2", "age": 50} {"_ id": ObjectId ("58d51f0e76002e9a38cccef1"), "age": 30} > db.students.find ({age: {$in: [23,340]}}) {"_ id": ObjectId ("58d50e6376002e9a38ccceec"), "name": "tom" "age": 23} {"_ id": ObjectId ("58d51cec76002e9a38ccceef"), "name": "x1", "age": 40} > db.students.find ({age: {$nin: [239,40]}) {"_ id": ObjectId ("58d5183976002e9a38ccceed"), "name": "xj"} {"_ id": ObjectId ("58d51b2776002e9a38ccceee"), "name": "xx" "Age": 35} {"_ id": ObjectId ("58d51cff76002e9a38cccef0"), "name": "x2", "age": 50} {"_ id": ObjectId ("58d51f0e76002e9a38cccef1"), "age": 30}

Combination condition: logical operation

$or: or operation

$and: and operation

$nor: inverse operation, returning all documents that do not meet the specified conditions

Syntax format:

{$or: [{},...]}

At least 2 conditional clauses

$not: non-operation

Only the $not format is different from the one above.

Perform a logical NOT operation to select documents that do not match expressions, including documents that do not have a specified key. The $not operator cannot be used independently and must be used with other operations (except $regex).

{field: {$not:}

> db.students.find ({$or: [{age: {$gt:30}}, {Age: {$gt:30}]}) {"_ id": ObjectId ("58d51b2776002e9a38ccceee"), "name": "xx", "Age": 35} {"_ id": ObjectId ("58d51cec76002e9a38ccceef"), "name": "x1", "age": 40} {"_ id": ObjectId ("58d51cff76002e9a38cccef0"), "name": "x2" "age": 50} > db.students.find ({$nor: [{age: {$gt:30}}]}) {"_ id": ObjectId ("58d50e6376002e9a38ccceec"), "name": "tom", "age": 23} {"_ id": ObjectId ("58d5183976002e9a38ccceed"), "name": "xj"} {"_ id": ObjectId ("58d51b2776002e9a38ccceee"), "name": "xx" "Age": 35} {"_ id": ObjectId ("58d51f0e76002e9a38cccef1"), "age": 30} > db.students.find ({age: {$not: {$gt:30}) {"_ id": ObjectId ("58d50e6376002e9a38ccceec"), "name": "tom", "age": 23} {"_ id": ObjectId ("58d5183976002e9a38ccceed"), "name": "xj"} {"_ id": ObjectId ("58d51b2776002e9a38ccceee") "name": "xx", "Age": 35} {"_ id": ObjectId ("58d51f0e76002e9a38cccef1"), "age": 30}

Element query

A query based on whether a specified field exists in the document

$exists:

Syntax format:

{filed: {$exists:}}

> db.students.find () {"_ id": ObjectId ("58d50e6376002e9a38ccceec"), "name": "tom", "age": 23} {"_ id": ObjectId ("58d5183976002e9a38ccceed"), "name": "xj"} {"_ id": ObjectId ("58d51b2776002e9a38ccceee"), "name": "xx", "Age": 35} {"_ id": ObjectId ("58d51cec76002e9a38ccceef"), "name": "x1" "age": 40} {"_ id": ObjectId ("58d51cff76002e9a38cccef0"), "name": "x2", "age": 50} {"_ id": ObjectId ("58d51f0e76002e9a38cccef1"), "age": 30} {"_ id": ObjectId ("58d5261d76002e9a38cccef2"), "age": ""} {"_ id": ObjectId ("58d5262a76002e9a38cccef3") "age": "null"} {"_ id": ObjectId ("58d5264576002e9a38cccef4"), "age": "Null"} {"_ id": ObjectId ("58d5271f76002e9a38cccef5"), "age": null} {"_ id": ObjectId ("58d5274b76002e9a38cccef6"), "age": ""} {"_ id": ObjectId ("58d527c176002e9a38cccef7") "age": null} > db.students.find ({name: {$exists:true}}) {"_ id": ObjectId ("58d50e6376002e9a38ccceec"), "name": "tom", "age": 23} {"_ id": ObjectId ("58d5183976002e9a38ccceed"), "name": "xj" {"_ id": ObjectId ("58d51b2776002e9a38ccceee"), "name": "xx" "Age": 35} {"_ id": ObjectId ("58d51cec76002e9a38ccceef"), "name": "x1", "age": 40} {"_ id": ObjectId ("58d51cff76002e9a38cccef0"), "name": "x2", "age": 50} > db.students.find ({name: {$exists:false}}) {"_ id": ObjectId ("58d51f0e76002e9a38cccef1"), "age": 30} {"_ id": ObjectId ("58d5261d76002e9a38cccef2") "age": ""} {"_ id": ObjectId ("58d5262a76002e9a38cccef3"), "age": "null"} {"_ id": ObjectId ("58d5264576002e9a38cccef4"), "age": "Null"} {"_ id": ObjectId ("58d5271f76002e9a38cccef5"), "age": null} {"_ id": ObjectId ("58d5274b76002e9a38cccef6"), "age": "} {" _ id ": ObjectId (" 58d527c176002e9a38cccef7 ") "age": null}

The key value is null query operation.

How to retrieve a document whose age key value is null, "$in" determines whether the key value is null, and "$exists" determines whether the document in the collection contains the key.

> db.students.find () {"_ id": ObjectId ("58d50e6376002e9a38ccceec"), "name": "tom", "age": 23} {"_ id": ObjectId ("58d5183976002e9a38ccceed"), "name": "xj"} {"_ id": ObjectId ("58d51b2776002e9a38ccceee"), "name": "xx", "Age": 35} {"_ id": ObjectId ("58d51cec76002e9a38ccceef"), "name": "x1" "age": 40} {"_ id": ObjectId ("58d51cff76002e9a38cccef0"), "name": "x2", "age": 50} {"_ id": ObjectId ("58d51f0e76002e9a38cccef1"), "age": 30} {"_ id": ObjectId ("58d5261d76002e9a38cccef2"), "age": ""} {"_ id": ObjectId ("58d5262a76002e9a38cccef3") "age": "null"} {"_ id": ObjectId ("58d5264576002e9a38cccef4"), "age": "Null"} {"_ id": ObjectId ("58d5271f76002e9a38cccef5"), "age": null} {"_ id": ObjectId ("58d5274b76002e9a38cccef6"), "age": ""} > db.students.find ({age: {$in: [null], $exists:true}}) {"_ id": ObjectId ("58d5271f76002e9a38cccef5") "age": null} > db.students.find ({age:null}) # this check contains documents {"_ id": ObjectId ("58d5183976002e9a38ccceed"), "name": "xj"} {"_ id": ObjectId ("58d51b2776002e9a38ccceee"), "name": "xx", "Age": 35} {"_ id": ObjectId ("58d5271f76002e9a38cccef5"), "age": null}

The following are not used much:

$mod: performs a modular operation on the specified element and returns the document with the specified remainder

$type: returns a document whose value of the specified field is of the specified type

Syntax format:

{filed: {$type:}}

Type: identify by digital

1:Doble

2:String

3:Object

Array,Binary data,Undefined,Boolean,Date

3. Update the document

MongoDB uses the update () method to update documents in the collection.

The db.mycoll.update () method is used to update existing documents.

> db.students.find ({name: "tom"}) {"_ id": ObjectId ("58d50e6376002e9a38ccceec"), "name": "tom", "age": 20} > db.students.update ({name: "tom"}, {$set: {age:25}}) > db.students.find ({name: "tom"}) {"_ id": ObjectId ("58d50e6376002e9a38ccceec"), "name": "tom" "age": 25} > db.students.update ({name: "tom"}, {$set: {name: "toms"}) > db.students.find ({name: "toms"}) {"_ id": ObjectId ("58d50e6376002e9a38ccceec"), "age": 25, "name": "toms"}

$set: the value of the modified field is the newly specified value. Syntax format:

{filed: value}, {$set: {filed: new_value}}

$unset: delete the specified field, syntax format

{filed:value}, {$unset: {filed1,filed2,...}}

$inc: increase

4. Delete operation

Delete document

The db.mycoll.remove () function is used to remove data from the collection.

Syntax format:

Db.collection.remove (

)

Parameter description:

Query: (optional) conditions for deleted documents.

JustOne: (optional) if set to true or 1

WriteConcern: (optional) the level at which the exception is thrown.

If no parameters are taken, all documents will be deleted by default

> db.students.find ({name: "toms"}) {"_ id": ObjectId ("58d50e6376002e9a38ccceec"), "age": 25, "name": "toms"} > db.students.remove ({name: "toms"}) > db.students.find ({name: "toms"})

Delete collection

Db.mycoll.droup ()

> show collectionsaystudentssystem.indexes > db.ay.drop () true > show collectionsstudentssystem.indexes >

Delete database

Db.dropDatabase () # Delete the current database

> dbtestdb > show dbslocal 0.078125GBsb (empty) students 0.203125GBtest (empty) testdb 0.203125GB > db.dropDatabase () {"dropped": "testdb", "ok": 1} > show dbslocal 0.078125GBsb (empty) students 0.203125GBtest (empty)

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