初学MongoDB实践笔记安装、创建数据库、保存及查询数据
MongoDB是一个可扩展、高性能的分布式文档存储数据库,由C 语言编写,旨在为web应用提供可扩展的高性能数据存【本文来自鸿网互联 (http://www.68idc.cn)】储解决方案。它的特点是高性能、易部署、易使用,存储数据非常方便。 Mongo DB 是目前在IT行业非常流
MongoDB是一个可扩展、高性能的分布式文档存储数据库,由C 语言编写,旨在为web应用提供可扩展的高性能数据存【本文来自鸿网互联 (http://www.68idc.cn)】储解决方案。它的特点是高性能、易部署、易使用,存储数据非常方便。
Mongo DB 是目前在IT行业非常流行的一种非关系型数据库(NoSql),其灵活的数据存储方式备受当前IT从业人员的青睐。Mongo DB很好的实现了面向对象的思想(OO思想),在Mongo DB中每一条记录都是一个Document对象。Mongo DB最大的优势在于所有的数据持久操作都无需开发人员手动编写SQL语句,直接调用方法就可以轻松的实现CRUD操作。
文档数据库介绍:
MongoDB数据库中一条记录是一个文档,他的数据结构由(field)和值(value)成对的组成。MongoDB文档类似于JSON对象。字段(域)的值可以包含其他文档、数组和文档数组。
如下图所示MongoDB文档结构:

使用文档数据库的优势如下:
在许多程序设计语言中,文档(即对象)适合原生数据类型;
嵌入式文档和数组减少昂贵的关系型关联需要;
动态数据结构模式支持流畅的可扩展多态性。
安装
官方网站:http://www.mongodb.org/downloads,下载Windows 64bit地址。
MongoDB在Windows 7上的安装运行很方便。直接下载、解压,然后运行bin/mongod 即可启动服务器,运行bin/mongo 即可运行命令行客户端。
我是使用默认安装到C盘Program Files\MongoDB 2.6 Standard目录下,为了方便学习,将其拷贝到C盘根目录下,为C:\MongoDB。
注意:请最好不要安装到C盘Program Files目录下,而且安装目录不要包含空格,否则,将麻烦些,也就是命令行参数每个参数要用“”括起来,例如:
repeat "I am hungry" now
命令会把字符串"I am hungry"分配给argv[1],把字符串"now"分配给argv[2]。
在启动MongoDB之前,我们必须新建一个存放mongoDB数据和日志的目录。数据库目录:C:\MongoDB\data\db\,日志目录:C:\MongoDB\data\。
启动服务
打开CMD窗口,进入到C:\MongoDB\bin目录下,运行服务端mongod.exe。
C:\MongoDB\bin>mongod.exe --dbpath=C:\MongoDB\data\db --directoryperdb --logpath=C:\MongoDB\data\logs --logappend
注:如果服务未启动成功,主要是两个原因,一是未建data\db\目录;以及防火墙不允许开放服务所需端口。
运行客户端
再打开一个CMD窗口,进入到C:\MongoDB\bin目录下,运行客户端mongo.exe来登录MongoDB。(要保持服务端mongod.exe的窗口不关闭)
Java开发数据库驱动
驱动Jar包链接地址,驱动ZIP包链接地址。https://github.com/mongodb/mongo-java-driver/releases
在客户端练习
删除用户:db.dropUser('username')
创建OA数据库:use OA
注:如果不做其他操作,则OA数据库是不会被创建的。
创建collections:OA.createCollection("mytest");
查看数据库:
> show dbs
OA 0.078GB
admin 0.078GB
db (empty)
local 0.078GB
test (empty)
查看Collection(相当于“表”):
> show collections
创建文档数据数据表,并插入数据记录。
> use OA
switched to db OA
> db.createCollection("doctest")
{ "ok" : 1 }
> db.doctest.save({id:1,name:'ttest1'});
WriteResult({ "nInserted" : 1 })
> db.doctest.save({id:2,name:'ttest1',code:'102'});
WriteResult({ "nInserted" : 1 })
> db.doctest.save({id:3,name:'ttest3',code:'103',class:'doc'});
WriteResult({ "nInserted" : 1 })
> db.doctest.save({id:4,name:'ttest4',code:'104'});
WriteResult({ "nInserted" : 1 })
查询
查询数据数量(count)
> db.doctest.find().count();
4
条件(=)查询,条件为:name="ttest1"。
> db.doctest.find({"name":"ttest1"});
{ "_id" : ObjectId("54a1003556a081db9d632745"), "id" : 1, "name" : "ttest1" }
{ "_id" : ObjectId("54a1005756a081db9d632746"), "id" : 2, "name" : "ttest1", "code" : "102" }
条件(>=)查询,条件为:id>3。
> db.doctest.find({id:{$gt:3}});
{ "_id" : ObjectId("54a100a056a081db9d632748"), "id" : 4, "name" : "ttest4", "code" : "104" }
> db.doctest.find({id:{$gte:3}});
{ "_id" : ObjectId("54a1008c56a081db9d632747"), "id" : 3, "name" : "ttest3", "code" : "103", "class" : "doc" }
{ "_id" : ObjectId("54a100a056a081db9d632748"), "id" : 4, "name" : "ttest4", "code" : "104" }
条件(in)查询,条件为:id in (2,3)。
> db.doctest.find({id:{$in:[2,3]}});
说明:$gt : > --(Greater than 的首字母)
$gte : >= --(Greater than or equal 的首字母)
$lt :
$lte :
$ne : != --(Not equal 的首字母)
推荐客户端工具
1. MongoVUE ,http://blog.mongovue.com/
数据库设计
MongoDB 无固定结构,每张表每段数据可以有不同的结构,这既是好处也是缺点,缺点在于你必须很了解MongoDB的表结构,这其实给维护人员带来一定的不适应和麻烦。
此问题也很容易解决,就是增加表结构定义表,用于说明各种情况下的结构定义,例如可配置审批单,就是比较适用。
嵌套式设计,例如审批单带有明细项目,其中,明细项目是多行数据内容,则操作如下:
>db.doctest.save({id:5,name:'ttest5',code:'106',detail:[{item:'测试卡1',type:'Card',acount:3},{item:'测试卡2',type:'Card',acount:5}]});
查询其中型号(Type)是“Mobile”的记录,在操作如下:
> db.doctest.find({"detail.type":"Mobile"});
{ "_id" : ObjectId("54a39ebdd8389293ac59e78a"), "id" : 6, "name" : "ttest6", "code" : "107", "detail" : [ { "item" : "员工卡1", "type" : "Card", "acount" : 3 }, { "item" : "测试手机", "type" : "Mobile", "acount" : 5 } ] }
查看审批单的设计:
> db.doctest.find();
查询内嵌文档
查询文档有两种方式,一种是完全匹查询,另一种是针对键值对查询!内嵌文档的完全匹配查询和数组的完全匹配查询一样,内嵌文档内键值对的数量,顺序都必须一致才会匹配,如下例:
针对内嵌文档特定键值对的查询是最常用的!通过点表示法来精确表示内嵌文档的键。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

It is impossible to view MongoDB password directly through Navicat because it is stored as hash values. How to retrieve lost passwords: 1. Reset passwords; 2. Check configuration files (may contain hash values); 3. Check codes (may hardcode passwords).

When developing an e-commerce website, I encountered a difficult problem: how to provide users with personalized product recommendations. Initially, I tried some simple recommendation algorithms, but the results were not ideal, and user satisfaction was also affected. In order to improve the accuracy and efficiency of the recommendation system, I decided to adopt a more professional solution. Finally, I installed andres-montanez/recommendations-bundle through Composer, which not only solved my problem, but also greatly improved the performance of the recommendation system. You can learn composer through the following address:

Detailed explanation of MongoDB efficient backup strategy under CentOS system This article will introduce in detail the various strategies for implementing MongoDB backup on CentOS system to ensure data security and business continuity. We will cover manual backups, timed backups, automated script backups, and backup methods in Docker container environments, and provide best practices for backup file management. Manual backup: Use the mongodump command to perform manual full backup, for example: mongodump-hlocalhost:27017-u username-p password-d database name-o/backup directory This command will export the data and metadata of the specified database to the specified backup directory.

Encrypting MongoDB database on a Debian system requires following the following steps: Step 1: Install MongoDB First, make sure your Debian system has MongoDB installed. If not, please refer to the official MongoDB document for installation: https://docs.mongodb.com/manual/tutorial/install-mongodb-on-debian/Step 2: Generate the encryption key file Create a file containing the encryption key and set the correct permissions: ddif=/dev/urandomof=/etc/mongodb-keyfilebs=512

Sorting index is a type of MongoDB index that allows sorting documents in a collection by specific fields. Creating a sort index allows you to quickly sort query results without additional sorting operations. Advantages include quick sorting, override queries, and on-demand sorting. The syntax is db.collection.createIndex({ field: <sort order> }), where <sort order> is 1 (ascending order) or -1 (descending order). You can also create multi-field sorting indexes that sort multiple fields.
