MongoDB - basic

本文涉及的产品
云数据库 MongoDB,独享型 2核8GB
推荐场景:
构建全方位客户视图
简介: mongoDB basicfrom:http://www.tutorialspoint.com/mongodbprject:https://github.com/chenxing12/l4mongodboverviewgetting-startcollectiondataTypein...

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
                }
        ]
}




唯有不断学习方能改变! -- Ryan Miao
目录
相关文章
|
Docker 容器
Mac Docker下安装与使用ShowDoc在线文档
Mac Docker下安装与使用ShowDoc在线文档
263 0
|
负载均衡 测试技术 应用服务中间件
性能测试常见瓶颈分析及调优方法总结
性能测试常见瓶颈分析及调优方法总结
625 0
|
10月前
|
人工智能 并行计算 调度
【AI系统】CUDA 编程模式
本文介绍了英伟达GPU的CUDA编程模型及其SIMT执行模式,对比了SIMD和SIMT的特点,阐述了SIMT如何提高并行计算效率和编程灵活性。同时简要提及了AMD的GPU架构及编程模型,包括最新的MI300X和ROCm平台。
393 5
|
API 云计算 开发者
使用宜搭平台带来的便利:技术解析与实践
【9月更文第8天】随着企业信息化建设的不断深入,业务流程自动化的需求日益增长。宜搭平台作为一种高效的应用构建工具,为企业提供了快速搭建各类业务系统的可能。本文将探讨使用宜搭平台给企业和开发者带来的便利,并通过具体的代码示例展示其优势。
385 11
|
关系型数据库 MySQL Docker
PolarDB-X安装部署初体验
本文档介绍了体验阿里云PolarDB-X分布式数据库的安装和使用过程。首先提到PolarDB-X在稳定性及性能上的优势,然后详细描述了在CentOS 7环境下遇到的Python版本不兼容和Docker容器iptables配置问题的解决方法。通过创建Python 3.8的虚拟环境解决PyYAML依赖问题,接着在解决Docker容器内部网络问题后,成功安装并启动PolarDB-X。文中强调PolarDB-X完全兼容MySQL,适合熟悉MySQL的用户,并分享了安装历史记录以供参考。
456 7
|
SQL 关系型数据库 Java
实时计算 Flink版操作报错之读取业务库数据,提示类型转换错误,该怎么处理
在使用实时计算Flink版过程中,可能会遇到各种错误,了解这些错误的原因及解决方法对于高效排错至关重要。针对具体问题,查看Flink的日志是关键,它们通常会提供更详细的错误信息和堆栈跟踪,有助于定位问题。此外,Flink社区文档和官方论坛也是寻求帮助的好去处。以下是一些常见的操作报错及其可能的原因与解决策略。
|
SQL 存储 OLAP
2G内存搞定一亿数据的分析引擎
EuclidOLAP是一个可以在低配置服务器上执行上亿数据量分析并且快速响应和支持复杂查询的开源OLAP数据库。
271 2
|
人工智能 安全 网络安全
防范网络攻击的最佳实践和安全意识培养
防范网络攻击是每个人和组织都需要关注的重要问题。通过建立综合的安全策略、采用适当的技术措施和培养安全意识,我们可以更好地保护个人隐私和组织数据免受网络攻击。未来,随着技术的不断进步,我们有信心在数字化时代创造更加安全的网络环境。
618 1
|
前端开发 JavaScript API
proxy配置
proxy配置
295 0
彻底搞懂微信小游戏中的分享功能
作为一个游戏,分享功能是必不可少的,尤其是对于一个微信小游戏来说,其最大的优势就是可以借助微信方便的进行分享。 在微信小游戏制作工具中,与分享有关的积木块并不多,一共就 5 块。
599 0