初学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

AI Hentai Generator
Generate AI Hentai for free.

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



Apple's latest releases of iOS18, iPadOS18 and macOS Sequoia systems have added an important feature to the Photos application, designed to help users easily recover photos and videos lost or damaged due to various reasons. The new feature introduces an album called "Recovered" in the Tools section of the Photos app that will automatically appear when a user has pictures or videos on their device that are not part of their photo library. The emergence of the "Recovered" album provides a solution for photos and videos lost due to database corruption, the camera application not saving to the photo library correctly, or a third-party application managing the photo library. Users only need a few simple steps

Solutions to resolve Navicat expiration issues include: renew the license; uninstall and reinstall; disable automatic updates; use Navicat Premium Essentials free version; contact Navicat customer support.

How to use MySQLi to establish a database connection in PHP: Include MySQLi extension (require_once) Create connection function (functionconnect_to_db) Call connection function ($conn=connect_to_db()) Execute query ($result=$conn->query()) Close connection ( $conn->close())

To handle database connection errors in PHP, you can use the following steps: Use mysqli_connect_errno() to obtain the error code. Use mysqli_connect_error() to get the error message. By capturing and logging these error messages, database connection issues can be easily identified and resolved, ensuring the smooth running of your application.

Using the database callback function in Golang can achieve: executing custom code after the specified database operation is completed. Add custom behavior through separate functions without writing additional code. Callback functions are available for insert, update, delete, and query operations. You must use the sql.Exec, sql.QueryRow, or sql.Query function to use the callback function.

To connect to MongoDB using Navicat, you need to: Install Navicat Create a MongoDB connection: a. Enter the connection name, host address and port b. Enter the authentication information (if required) Add an SSL certificate (if required) Verify the connection Save the connection

Through the Go standard library database/sql package, you can connect to remote databases such as MySQL, PostgreSQL or SQLite: create a connection string containing database connection information. Use the sql.Open() function to open a database connection. Perform database operations such as SQL queries and insert operations. Use defer to close the database connection to release resources.

Use the DataAccessObjects (DAO) library in C++ to connect and operate the database, including establishing database connections, executing SQL queries, inserting new records and updating existing records. The specific steps are: 1. Include necessary library statements; 2. Open the database file; 3. Create a Recordset object to execute SQL queries or manipulate data; 4. Traverse the results or update records according to specific needs.
