mongoDB basic

from:http://www.tutorialspoint.com/mongodb
prject:https://github.com/chenxing12/l4mongodb

  1. overview
  2. getting-start
  3. collection
  4. dataType
  5. insert
  6. find

Overview

MongoDB is a cross-platform, document oriented database that provides, high
performance, high availability, and easy scalability. MongoDB works on concept
of collection and document.

Database

Database is a physical container for collections. Each database gets its own set
of files on the file system. A single MongoDB server typically has multiple
databases.

Collection

Collection is a group of MongoDB documents. It is the equivalent of an RDBMS
table. A collection exists within a single database. Collections do not enforce
a schema. Documents with a collection can have different fields. Typically, all
documents in a collection are of similar or related purpose.

Document

A document is a set of key-value pairs. Documents have dynamic schema. Dynamic
schema means that documents in the same collection do not need to have the same
set of fields or structure, and common fields in a collection's documents may
hold different types of data.

Below given table shows the relationship of RDBMS terminology with MongoDB

RDBMS MongoDB
Database Database
Table Collection
Tuple/Row Document
column Field
Table Join Embedded Documents
Table Join Primary Key(Default key _id provided by mongodb itself)

Sample document

Below given example shows the document structure of a blog site which is simply
a comma separated key value pair.

{
_id: ObjectId(7df78ad8902c)
title: 'MongoDB Overview',
description: 'MongoDB is no sql database',
by: 'tutorials point',
url: 'http://www.tutorialspoint.com',
tags: ['mongodb', 'database', 'NoSQL'],
likes: 100,
comments: [
{
user:'user1',
message: 'My first comment',
dateCreated: new Date(2011,1,20,2,15),
like: 0
},
{
user:'user2',
message: 'My second comments',
dateCreated: new Date(2011,1,25,7,45),
like: 5
}
]
}

Getting-Start

top

Database

check all the databases:

> show dbs
local 0.000GB
mrf 0.000GB
test 0.005GB

create database: for example create mydb

> use mydb
switched to db mydb
> show dbs
local 0.000GB
mrf 0.000GB
test 0.005GB

The database mydb has not been created, because the db is empty,
You must create at lest one collection next.For example:

>
> use mydb
switched to db mydb
> show dbs
local 0.000GB
mrf 0.000GB
test 0.005GB
>
> show collections
> db.user.insert({name:"Ryan"})
WriteResult({ "nInserted" : 1 })
> show dbs
local 0.000GB
mrf 0.000GB
mydb 0.000GB
test 0.005GB

check current database:

> db
mydb

switch db:

> db
mydb
> use test
switched to db test
> db
test

drop database:

> show dbs
local 0.000GB
mrf 0.000GB
mydb 0.000GB
test 0.005GB
> use mydb
switched to db mydb
> db.dropDatabase()
{ "dropped" : "mydb", "ok" : 1 }
> show dbs;
local 0.000GB
mrf 0.000GB
test 0.005GB

collection

top

create collection

when you insert data, if the collection not exists, it will be created automatically:

> show collections
restaurants
test
> db.mycollection.insert({name:"test"})
WriteResult({ "nInserted" : 1 })
> show collections
mycollection
restaurants
test

Of course, there is other way to create a specify collection:

Syntax

Basic syntax of createCollection() command is as follows:

db.createCollection(name, options)

In the command, name is the name of collection created, Options is a document
and used to specify configuration of collection.

Options parameter is optional, so you need to specify only name of the collection.
Following is the list of options you can use:

Filed Type Description
capped Boolean (Optional) If true, enables a capped collection. Capped collection is a collection fixed size collection that automatically overwrites its oldest entries when it reaches its maximum size. If you sepecify true, you need specify size parameter too
autoIndexID Boolean (Optional) If true, automatically create index on _id filed. Default value is false
size number (Optional) Specify a maximum size in bytes for a capped collection. If capped is true, then you need specify this filed also
max number (Optional) Specifies the maximum number of documents allowed in the capped collection.

while inserting the document , MongoDB first checks size filed of capped collection, then it checks max filed.

Example

> db.mycollection.drop()
true
> show collections
restaurants
test
>
>
> db.createCollection("mycollection")
{ "ok" : 1 }
> show collections
mycollection
restaurants
test
>
> db.createCollection("mycol",{capped:true,autoIndexID:true,size:6142800, max:10000})
{ "ok" : 1 }
> show collections
mycol
mycollection
restaurants
test
>

drop()

> use test
switched to db test
> show collections
mycol
mycollection
restaurants
test
> db.mycol.drop()
true
> show collections
mycollection
restaurants
test

DataType

  1. top

MongoDB supports many datatypes whose list is given below:

String : This is most commonly used datatype to store the data. String in mongodb must be UTF-8 valid.
Integer : This type is used to store a numerical value. Integer can be 32 bit or 64 bit depending upon your server.
Boolean : This type is used to store a boolean (true/ false) value.
Double : This type is used to store floating point values.
Min/ Max keys : This type is used to compare a value against the lowest and highest BSON elements.
Arrays : This type is used to store arrays or list or multiple values into one key.
Timestamp : ctimestamp. This can be handy for recording when a document has been modified or added.
Object : This datatype is used for embedded documents.
Null : This type is used to store a Null value.
Symbol : This datatype is used identically to a string however, it's generally reserved for languages that use a specific symbol type.
Date : This datatype is used to store the current date or time in UNIX time format. You can specify your own date time by creating object of Date and passing day, month, year into it.
Object ID: This datatype is used to store the document’s ID.
Binary data : This datatype is used to store binay data.
Code : This datatype is used to store javascript code into document.
Regular expression : This datatype is used to store regular expression

Insert

  1. top

MongoDB insert option:

> show dbs;
local 0.000GB
mrf 0.000GB
test 0.005GB
> use test
switched to db test
> show collections;
mycollection
restaurants
test
>
>
> db.mycollection.insert({
title:"MongoDB Overview",
description:'MongoDB is no sql database',
by:'tutorials point',
url:'http://www.tutorialspoint.com',
tags:['mongodb','database','NoSQL'],
likes:100
})
WriteResult({ "nInserted" : 1 })
>
> db.mycollection.find()
{ "_id" : ObjectId("577e0dce99da0904659393c0"), "title" : "MongoDB Overview", "description" : "MongoDB is no sql databas
e", "by" : "tutorials point", "url" : "http://www.tutorialspoint.com", "tags" : [ "mongodb", "database", "NoSQL" ], "lik
es" : 100 }
> db.mycollection.find().pretty()
{
"_id" : ObjectId("577e0dce99da0904659393c0"),
"title" : "MongoDB Overview",
"description" : "MongoDB is no sql database",
"by" : "tutorials point",
"url" : "http://www.tutorialspoint.com",
"tags" : [
"mongodb",
"database",
"NoSQL"
],
"likes" : 100
}
>

Here mycollections is our collection name, as created in previous tutorial. If the
collection doesn't exist in the database, then MongoDB will create this collection
adn then insert document into it.

In the inserted document if we don't specify the _id parameter, then MongoDB
assigns an unique ObjectId for this document.

_id is 12 bytes hexadecimal number unique for every document in a collection.
12 Bytes are dived as follows :

_id: ObjectId(4 bytes timestamp, 3 bytes machine id, 2 bytes process id, 3 bytes incrementer)

To insert multiple documents in single query, you can pass an array of documents
in insert() command.

Example

db.post.insert([
{
title: 'MongoDB Overview',
description: 'MongoDB is no sql database',
by: 'tutorials point',
url: 'http://www.tutorialspoint.com',
tags: ['mongodb', 'database', 'NoSQL'],
likes: 100
},
{
title: 'NoSQL Database',
description: 'NoSQL database doesn\'t have tables',
by: 'tutorials point',
url: 'http://www.tutorialspoint.com',
tags: ['mongodb', 'database', 'NoSQL'],
likes: 20,
comments: [
{
user:'user1',
message: 'My first comment',
dateCreated: new Date(2013,11,10,2,35),
like: 0
}
]
}
])

find()

top

The find() Method

To query data from MongoDB collection, you need to user MongoDB's find() method.

Syntax

Basic syntax of find() method id as follows:

db.collection_name.find()

find()method will display all the documents in a non structured way.

The pretty() Method

To display the results in a formatted way, you can use pretty() method.

db.collection_name.find().pretty()

Example

> show collections
mycollection
post
restaurants
test
> db.post.find().pretty()
{
"_id" : ObjectId("577e11fd502847799b05f062"),
"title" : "MongoDB Overview",
"description" : "MongoDB is no sql database",
"by" : "tutorials point",
"url" : "http://www.tutorialspoint.com",
"tags" : [
"mongodb",
"database",
"NoSQL"
],
"likes" : 100
}
{
"_id" : ObjectId("577e11fd502847799b05f063"),
"title" : "NoSQL Database",
"description" : "NoSQL database doesn't have tables",
"by" : "tutorials point",
"url" : "http://www.tutorialspoint.com",
"tags" : [
"mongodb",
"database",
"NoSQL"
],
"likes" : 20,
"comments" : [
{
"user" : "user1",
"message" : "My first comment",
"dateCreated" : ISODate("2013-12-10T10:35:00Z"),
"like" : 0
}
]
}
>

RDBMS Where Clause Equivalents in MongoDB

To query the document on the basis of some codition, you can use following
options:

Options Syntax Example RDBMS Equivalent
Equal {\<key\>:\<value\>} db.mycol.find({'by':'abc'}).pretty() where by='abc'
Less Than {\<key\>:{$lt:\<value\>}} db.mycol.find({'likes':{$lt:50}}).pretty() where likes < 50
Less Than Equals {\<key\>:{$lte:\<value\>}} db.mycol.find({'likes':{$lte:50}}).pretty() where likes <= 50
Greater Than {\<key\>:{$gt:\<value\>}} db.mycol.find({'likes':{$gt:50}}).pretty() where likes > 50
Greater Than Equals {\<key\>:{$gte:\<value\>}} db.mycol.find({'likes':{$gte:50}}).pretty() where likes >= 50
Not Equals {\<key\>:{$ne:\<value\>}} db.mycol.find({'likes':{$ne:50}}).pretty() where likes != 50

Example

> db.mycol.find().pretty()
{
"_id" : ObjectId("577e19c5502847799b05f064"),
"title" : "MongoDB Overview",
"description" : "MongoDB is no sql database",
"by" : "tutorials point",
"url" : "http://www.tutorialspoint.com",
"tags" : [
"mongodb",
"database",
"NoSQL"
],
"likes" : 100
}
{
"_id" : ObjectId("577e19c5502847799b05f065"),
"title" : "NoSQL Database",
"description" : "NoSQL database doesn't have tables",
"by" : "tutorials point",
"url" : "http://www.tutorialspoint.com",
"tags" : [
"mongodb",
"database",
"NoSQL"
],
"likes" : 20,
"comments" : [
{
"user" : "user1",
"message" : "My first comment",
"dateCreated" : ISODate("2013-12-10T10:35:00Z"),
"like" : 0
}
]
}
>
> db.mycol.find({'likes':{$gt:50}}).pretty()
{
"_id" : ObjectId("577e19c5502847799b05f064"),
"title" : "MongoDB Overview",
"description" : "MongoDB is no sql database",
"by" : "tutorials point",
"url" : "http://www.tutorialspoint.com",
"tags" : [
"mongodb",
"database",
"NoSQL"
],
"likes" : 100
}
> db.mycol.find({'likes':{$lt:50}}).pretty()
{
"_id" : ObjectId("577e19c5502847799b05f065"),
"title" : "NoSQL Database",
"description" : "NoSQL database doesn't have tables",
"by" : "tutorials point",
"url" : "http://www.tutorialspoint.com",
"tags" : [
"mongodb",
"database",
"NoSQL"
],
"likes" : 20,
"comments" : [
{
"user" : "user1",
"message" : "My first comment",
"dateCreated" : ISODate("2013-12-10T10:35:00Z"),
"like" : 0
}
]
}

AND in MongoDB

Syntax
In the find() method if you pass multiple keys by separating them by ',' then
MongoDB treats itAND condition. Basic syntax of AND is shown below:

db.mycol.find({ keys:value, key2:value2 }).pretty()

Example:

Below given example will show all the tutorials written by and
whose title is 'MongoDB OVerview':

> db.mycol.find({"by":"tutorials point","title":"MongoDB Overview"}).pretty()
{
"_id" : ObjectId("577e19c5502847799b05f064"),
"title" : "MongoDB Overview",
"description" : "MongoDB is no sql database",
"by" : "tutorials point",
"url" : "http://www.tutorialspoint.com",
"tags" : [
"mongodb",
"database",
"NoSQL"
],
"likes" : 100
}

For the above given example equivalent where clause will be
where by='tutorials point' AND title = 'MongoDB Overview'.
You can pass any number of key, value pairs in find clause.

OR in MongoDB

Syntax

To query documents based on the OR condition, you need to use $or keyword.
Basic syntax of OR is shown below −

>db.mycol.find(
{
$or: [
{key1: value1}, {key2:value2}
]
}
).pretty()

Example

> db.mycol.find(
{
$or:[
{"title":"MongoDB Overview"},{"likes":20}
]
}).pretty() {
"_id" : ObjectId("577e19c5502847799b05f064"),
"title" : "MongoDB Overview",
"description" : "MongoDB is no sql database",
"by" : "tutorials point",
"url" : "http://www.tutorialspoint.com",
"tags" : [
"mongodb",
"database",
"NoSQL"
],
"likes" : 100
}
{
"_id" : ObjectId("577e19c5502847799b05f065"),
"title" : "NoSQL Database",
"description" : "NoSQL database doesn't have tables",
"by" : "tutorials point",
"url" : "http://www.tutorialspoint.com",
"tags" : [
"mongodb",
"database",
"NoSQL"
],
"likes" : 20,
"comments" : [
{
"user" : "user1",
"message" : "My first comment",
"dateCreated" : ISODate("2013-12-10T10:35:00Z"),
"like" : 0
}
]
}

Using AND and OR together

####Example
Below given example will show the documents that have likes greater than 10
and whose title is either 'MongoDB Overview' or by is 'tutorials point':
Equals:where likes>10 AND (by = 'tutorials point' OR title = 'MongoDB Overview')

> db.mycol.find({
"likes": {$gt:10},
$or: [
{"by": "tutorials point"}, {"title": "MongoDB Overview"}
]
}).pretty()
{
"_id" : ObjectId("577e19c5502847799b05f064"),
"title" : "MongoDB Overview",
"description" : "MongoDB is no sql database",
"by" : "tutorials point",
"url" : "http://www.tutorialspoint.com",
"tags" : [
"mongodb",
"database",
"NoSQL"
],
"likes" : 100
}
{
"_id" : ObjectId("577e19c5502847799b05f065"),
"title" : "NoSQL Database",
"description" : "NoSQL database doesn't have tables",
"by" : "tutorials point",
"url" : "http://www.tutorialspoint.com",
"tags" : [
"mongodb",
"database",
"NoSQL"
],
"likes" : 20,
"comments" : [
{
"user" : "user1",
"message" : "My first comment",
"dateCreated" : ISODate("2013-12-10T10:35:00Z"),
"like" : 0
}
]
}

DB Intro - MongoDB Basic的更多相关文章

  1. DB Intro - MongoDB User

    MongoDB 3.0 用户创建   摘要: MongoDB 3.0 安全权限访问控制,在添加用户上面3.0版本和之前的版本有很大的区别,这里就说明下3.0的添加用户的方法. 环境.测试: 在安装Mo ...

  2. DB Intro - MongoDB Relations

    https://www.quackit.com/mongodb/tutorial/mongodb_create_a_relationship.cfm

  3. MongoDB - basic

    mongoDB basic from:http://www.tutorialspoint.com/mongodb prject:https://github.com/chenxing12/l4mong ...

  4. DB Intro - MySQL and MongoDB

    mysql> CREATE TABLE tutorials_tbl( tutorial_id INT, tutorial_title VARCHAR(100), tutorial_author ...

  5. [React] 04 - Intro: mongoDB becomes popular

    Ref: Linux平台安装MongoDB - 菜鸟教程 安装:sudo apt-get install mongodb 安装完毕产生: ls /etc/init.d/mongodb 配置:vim / ...

  6. mongodb数据库调试问题:‘db object already connecting, open cannot be called multiple times’

    在微博小系统的调试过程中: (1)登入登出可以正常显示,就是在注册的时候网络连接突然停止,但是用户名和密码已经存入数据库中,报错为:undefined is not a function 错误主要指向 ...

  7. 连接有密码的mongodb

    mongoose: db.openSet("mongodb://admin:pass@192.168.1.100:27017/mydb");

  8. [Reproduced works]MongoDB Unauthorized Access Vulnerability

    mongodb未授权访问漏洞 catalogue 1. mongodb安装 2. 未授权访问漏洞 3. 漏洞修复及加固 4. 自动化检测点 1. mongodb安装 apt-get install m ...

  9. mongodb未授权访问漏洞

    catalogue . mongodb安装 . 未授权访问漏洞 . 漏洞修复及加固 . 自动化检测点 1. mongodb安装 apt-get install mongodb 0x1: 创建数据库目录 ...

随机推荐

  1. 第01章-Spring之旅

    一.简化Java开发 1. Spring的主要特性 依赖注入DI和面向切面编程AOP. 2. 关键策略 轻量级和最小侵入性编程:POJO 松耦合:DI和AOP 声明式编程:切面和惯例 减少样板式代码: ...

  2. 编写高质量代码改善C#程序的157个建议——建议5: 使用int?来确保值类型也可以为null

    建议5: 使用int?来确保值类型也可以为null 基元类型为什么需要为null?考虑两个场景: 1)数据库中一个int字段可以被设置为null.在C#中,值被取出来后,为了将它赋值给int类型,不得 ...

  3. Head First Python之人人都爱列表(1-初识Python)

    IDLE 内置函数==BIF==built-in function 默认地,内置函数都是紫色,字符串是绿色,关键字是橙色. tab:自动补全 Alt-P:前一个 Alt-N:下一个 列表的特性 列表看 ...

  4. struts2中错误提示:There is no Action mapped for namespace / and action name

    当在struts2中运行时出现如上所述错误时: 1.在src目录下创建struts.xml一定要注意拼写 2.struts.xml文件中引入和extend是否正确 3.在web.xml 中<we ...

  5. 干掉MessageBox,自定义弹出框JMessbox (WindowsPhone)

    先上效果图                                               QQ退出效果                                           ...

  6. Jquery的动画

    $下载链接详情点击Jquery-day01查看官方网站下载地址 Jquery-day02 1.Jquery动画使用animate-(JQ-2.1) <!DOCTYPE html> < ...

  7. f(!gotop.length) return false;

    if (!$("p").length) return; if语句接收一个布尔值,如果布尔值为true则执行接下来的语句,布尔值为false则执行else关键词后的语句. JavaS ...

  8. EF进阶篇(三)——上下文

    前言 上下文,到底什么是上下文,且听我仔细吹来. 内容 在对EF实体进行关系操作的时候,第一步需要我们创建上下文实例对象,然后根据实体的变化进而通过上下文对该实体进行状态的修改,我的理解就是上下文就是 ...

  9. EF进阶篇(一)——概述

    前言 以前在ITOO里面和图书馆项目开发的时候,采用的这个技术,但是总是对上下文那里不是特别清楚.上下文这个概念很是模糊,所以这次再次拿起这个技术点儿,然后复习了一遍,发现我以前想的好简单. 内容 E ...

  10. C#委托笔记

    参考: 第一篇:http://www.tracefact.net/tech/009.html 第二篇:http://www.tracefact.net/tech/029.html 1.委托相当于一种参 ...