MongoDB Authoritative Guide Second Edition learning note two

Source: Internet
Author: User
Tags mongodb server mongo shell

Data Type

MongoDB adds some additional data types based on preserving the JSON basic key / value pairs feature.

Null

Null is used to represent a null or nonexistent field:{"x":null}

Boolean type

The Boolean type has two values of true and false {"x":True}

Numerical

The shell defaults to a value of type float. {"x":3.14} or {"x":3}

for integer values, you can use the The Numberint class (representing a 4 - byte signed integer) or numberlong class (representing 8 Character signed integer) {"X": Numberint ("3")} {"x": Numberlong ("3")}

string

Utf-8 strings can be represented as string types of data: {"x": "Foobar"}

Date

The date is stored as the number of milliseconds elapsed since the beginning of the new century, and the time zone is not stored: {"x":new date ()}

When you create a Date object, you should use new date () instead of date (), which returns a string representation of the date, not a date object. This result has nothing to do with MongoDB , it is the working mechanism of JS decision. Because there is no match between the date and the string, there are a lot of problems when performing almost all operations such as pruning and checking.

> Db.blog.insert ({"x""ninserted": 1 })>"_id": ObjectId ("584ea42d3bb80d550a5914fe" ), "x": "Mon Dec 21:20:45 gmt+0800 (CST)" }> Db.blog.insert ({"x":new"ninserted": 1 })>"_id": ObjectId ("584ea42d3bb80d550a5914fe"), "X": "Mon Dec 21:20:45 gmt+0800 (CST)"  "_id": ObjectId ("584ea4573bb80d550a5914ff"), "X": Isodate ("2016-12-12t13:21:27.361z")}
Regular Expressions

When querying, use regular expressions as qualification {"X":/foobar/i}

Array

A data list or array set can represent an array: {"x": ["a", "B", "C"]}

An array is a set of values that can be manipulated as an ordered object (such as a list, stack, or queue) or as an unordered object, such as a dataset.

The array can contain elements of different data types {"Things": ["pie", 3.14]} . As long as all the values supported by the regular key/ value pair can be the values of the array, arrays can even be nested.

Inline document

The document can be embedded in other documents, the nested document as the value of the parent document: {"x": {"foo", "Bar"}}

with inline documentation, you can make your data organization more natural, without having to store key/value pairs in a flat structure .

> post={... "User":{... "Name": "Yyb",... "Address":{... "Street": "123 Park Street",... "City": "Anytown",... "State": "NY"...} ...   } ... } {        "User" : {                "Name": "Yyb",                "Address" : {                        "Street": "123 Park Street",                        "City": "Anytown",                        "State": "NY"                }        }}>Db.blog.insert (POST) writeresult ({"Ninserted": 1 })>Db.blog.find () {"_id": ObjectId ("584ea90fce4f8e1bf30ba07d"), "user": {"name": "Yyb", "address": {"street": "123 Park Street", "City ":" Anytown "," state ":" NY "}}}
ObjectID

the object ID is a one - byte ID, which is the unique identifier of the document {"X": ObjectId ()}

MongoDB The document stored in must have a " _id "key. Ensure that each document in the collection is uniquely identified.

The value of this key can be any type, the default is a The ObjectId object. Object IDs are designed to be lightweight, and different machines can be easily generated using a globally unique homogeneous method. This is important for generating unique identifiers in the Shard environment.

the first 4 bytes of ObjectId are timestamps that start in the standard era, in seconds. This will bring some useful properties.

    • The timestamp , combined with the subsequent 5 bytes, provides the uniqueness of the second level.
    • since the timestamp is in front, this means that the Objectid is roughly sorted in the order in which they were inserted.
    • this 4- Byte also implies the time when the document was created. Most drivers will provide a way to Get this information from ObjectId.

The next 3 bytes are the unique identifier of the host on which it resides. This is usually the hash value of the machine host name. This ensures that different hosts generate different objectIdand do not create conflicts.

to ensure that multiple processes concurrently on the same machine produce The ObjectId is unique, and the next two bytes come from The process identifier PIDthat generated the ObjectId process.

The first 9 bytes guarantee that the ObjectId generated by different processes of different machines in the same second is unique. The last 3 bytes are an automatically incremented counter to ensure that the same process is not the same as the ObjectId produced in the same second . A maximum of one second allows each process to have 2563 different ObjectId.

If you insert a document without the "_id" key, the system will automatically create one for you. Can be done by the MongoDB service, but it is usually done by the driver on the client.

Binary data

Binary data is a string of any byte. It cannot be used directly in the shell . If you want to characters a non- utf-8 Word in the database, the binary data is the only way.

Code

The query and the document can contain any JS code {"x":function() {/*... */}}

In addition, there are several types in which most cases are used internally (or superseded by other types) only.

using the MongoDB shell

Connect the shell to any MongoDB instance:MONGO machine Name: Port/Database name

Below use my Linux connection to my Windows

[Email protected] mongodb]#/bin/mongo 192.168.1.111:27017/test mongodb Shell version:3.2.10Connecting to:192.168.1.111:27017/testServer has startup warnings:2016-12-12t14:14:40.558+0800I CONTROL [Initandlisten]2016-12-12t14:14:40.558+0800 I control [Initandlisten] * * warning:access CONTROL is not enabled forThe database.2016-12-12t14:14:40.558+0800 I CONTROL [Initandlisten] * *Read and write access to data and configuration is unrestricted.2016-12-12t14:14:40.558+0800I CONTROL [Initandlisten]>Show Dbsadmin0. 000GBlocal0. 000GBtest0. 000GB>Db.test.find ()> Db.test.insert ({"X": 100}) Writeresult ({"Ninserted": 1 })> >Db.test.find () {"_id": ObjectId ("584fe47a36b03fda10897c99"), "X": 100}

See the effects in my windows

Do not connect to any database at startup , start the shellwith the--nodb parameter, and run new Mongo (hostname) when needed when it is started command, you can connect to the desired Mongod up. You can use these commands at any time to connect to a different database or server.

 [[email protected] mongodb]#./bin/mongo--nodbmongodb Shell version:  3.2.10> conn=new  Mongo ("192.168.1.111:27017" ) connection to  192.168.1.111:27017> db=conn.getdb ("test" ) test  > Db.test.find () {" _id ": ObjectId (" 584fe47a36b03fda10897c99 " ), "x": [+] 

The Shell has built-in Help documentation that can be viewed using the Assist command , which can be viewed through db.help () to help at the database level, using Db.foo.help () View the collection-level help and use the Db.foo.update method to view the JS Implementation code for the function.

>Help Db.help () Help on DB Methods Db.mycoll.help () Help on Collection Me        Thods sh.help () sharding helpers rs.help () replica set helpers Help Admin administrative help and connect connecting to a DB Help help K                      Eys Key Shortcuts Help Misc misc Things to know help Mr MapReduce Show DBS Show database names show collections show Collecti ONSinchCurrent database show users show UsersinchCurrent database show profiles show most recent system.profile entries withTime >=1ms show logs show the accessible logger names show log [name] prints O UT the last segment of loginchMemory, ' global ' isdefault Use<db_name>Set Current database Db.foo.find () List ObjectsinchCollection Foo db.foo.find ({a:1}) List objectsinchFoo where a = = 1It result of the last line evaluated; further iterate Dbquery.shellbat Chsize= X SetdefaultNumber of items to display on shell exit quit the MONGO shell
Executing scripts using the shell

The MONGO Shell executes the incoming script sequentially, and then exits.

E:\Program files\mongodb\server\3.4\bin>MONGO Js1.jsmongodb Shell version v3. 4.0-rc3-7-ge24e12cconnecting to:mongodb://127.0.0.1:27017MongoDB Server version:3.4.0- rc3-7- in the Script1.js

First: The location of the script should be placed in the directory where the Mongo.exe resides, i.e. the bin directory. Second, if the environment variables are configured, it is not possible to MONGO Js1.js directly. Like what:

c:\users\yang>MONGO js1.js2016-12-13t21:25:36.265+0800 E-[main] file [js1.js] doesn 't existfailed to Load:js1.js

Run the script using Mongod on the specified host /port , you need to specify the address first, and then follow the name of the script file.

Use the print () function in your script to output the content to standard output so that you can use pipeline commands in the shell. If you send the output pipeline of a shell script to another command that uses the--quiet option, you can let the shell not print the "MongoDB Shell version ..." prompt.

[Email protected] bin]#./mongo--quiet 192.168.1.111:27017/test js1.jsi like to read and study

You can use the load () function to Run scripts from the interactive shell:

> Load ("js1.js") I like to read and studytrue

DB variables, as well as other global variables, can be accessed in the script . However,Shell helper functions (such as "usedb" and "show Collections") cannot be used in a file. However, these auxiliary functions have the corresponding js function.

You can use a script to inject variables into the shell

 /*  ** connects to the specified database and points the db to this connection  */ var  connectto=function   (port,dbname) { if  (! Port) {Port  =27017;}  if  (! dbname) {dbname  = "Test" ;} DB  =connect ("localhost:" +port+ "/" +dbname ");  return   db;}  
typeof connecttoundefined> Load ("defineconnectto.js")truetypeof  ConnectTo  function

if the Shell loaded in this script, ConnectTo The function is ready to use.

MongoDB Authoritative Guide Second Edition learning note two

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.