search
HomeDatabaseMysql TutorialMongoDB+node-mongoskin学习笔记

特点 无模式 MongoDB 中的每一条文档,都是一个 JSON 对象,因此你无需预定义一个集合的结构,集合中的每个文档也可以有不同的结构。 异步写入 MongoDB 默认所有的写操作都是『不安全』的,即当请求被 MongoDB 收到时,不等写入操作完成,就返回一个『成功』

特点

无模式

MongoDB 中的每一条文档,都是一个 JSON 对象,因此你无需预定义一个集合的结构,集合中的每个文档也可以有不同的结构。

异步写入

MongoDB 默认所有的写操作都是『不安全』的,即当请求被 MongoDB 收到时,不等写入操作完成,就返回一个『成功』的响应。 这是默认的行为,当然你设置一些选项,让操作等待等待写入完成后再返回响应。不过对于大多数应用,这种『不安全』已经足够安全了。

简单查询

MongoDB 只支持简单的查询,MongoDB 只储存数据,更多的逻辑应该在应用中解决。因此 MongoDB 有着简单的且在各编程语言下高度一致的 API 接口。

无需运维

MongoDB 几乎没有什么选项可以设置,集群也是设置一次之后就可以自动地解决故障,极少需要维护。

安装和备份

运行 mongod 启动数据库,运行 mongo 启动客户端 Shell,。

MongoDB 被设计运行于 64bit 的操作系统,在 32bit 的情况下,数据文件最大限制为 2GiB.

MongoDB 在运行时并不会实时地将修改写入磁盘,因此在关闭服务器时需要给 MongoDB 时间将所有数据写入磁盘。当出现服务器突然掉电的情况时,MongoDB 的数据库文件会损坏,需要进行修复才能重新运行,这个过程中会丢失掉电时正在进行的写入操作。在对运行中的 MongoDB 进行备份时,需要使用自带的 mongodump 工具,不能直接复制其数据库文件。

设计文档结构

ObjectID

MongoDB 会为每一个文档默认添加一个名为 _id, 类型为 Object 的字段,这个字段用来唯一地标识每一个文档。这个 ID 通过时间,服务器,进程号被生成,甚至可以认为是全世界唯一的。
除了 MongoDB 默认为 _id 添加 ObjectID, 你也可以自己在文档中创建 ObjectID, 来起到唯一地标识某个对象的功能。

查询和更新

所谓『增删查改』在 MongoDB 里对应:
find/findOne: 查询
update/save: 修改
insert/save: 新增
remove: 删除

在 MongoDB 中,操作符以 $ 开头,主要分为三类:查询操作符,更新操作符,聚合查询操作符。

查询操作符

用于 find 和 update 中的查询器,如 $gt(大于), $ne(不等于), $in(匹配几个值之一), 逻辑运算:$and, $not。

更新操作符

用于 update 中的更新器,如 $inc(对数字进行增量), $set(修改文档的一部分), $unset(删除一个字段).
MongoDB 对嵌入式的文档和数组有非常好的支持:$addToSet(向集合中添加元素), $push(向数组添加元素), $pull(从数组移除元素).

聚合查询(Aggregation)

类似于 SQL 数据库中的 GROUP, 提供统计和计算的功能,要多强大有多强大,毕竟可以直接在数据库中运行 JavaScript 代码,不过因为性能的关系,不适合在应用中频繁调用。

查询命令还有几个选项

limit: 限制返回的结果数
skip: 跳过一些结果
sort: 对结果进行排序
fields: 只返回指定的字段

MongoDB可以方便的把一些本来MySQL需要通过一对多关系关联的数据通过数组+对象的方式作为一个文档存储到一个Collections里面,并且提供了各种API支持对一个文档里面的数组进行操作。

MongoDB常用查询方法与在node中的体现:

1、数据库连接

MongoDB:mongo -u username -p password host:port/dbs
Node+MongoSkin: require(“mongoskin”).db(username:password@host:port/dbs);

2、索引

person.ensureIndex({“name”:1},{“unique”:true}, callback);

第一个参数是selector,第二个参数是选项,有unique(唯一索引)等mongoDB索引选项。
ensureIndex先查找是否存在这个索引,如果不存在,则建立索引,因此不会出现重复建立的情况。

3、新建/增加数据

person.save({“name”:”jobs”, age:32, gender:”male”}, callback);
person.save({“name”:”tim”, age:29, gender:”male”}, callback);

db.集合名.insert({name:'xiaoxiao',age:2},function(error,result){}

4、查询

findOne方法:查询符合selector条件的结果,取第一条给callBack,err是错误信息,如果没有错误,则为undefined,data数据为一个JS对象。

person.findOne({“name“:”jobs”}), callBack(err, data));

find方法:查询符合selector条件,并且还可以加入一系列参数,最后通过toArray方法,把数据生成数组的方式传递给callback。
person.find({“gender”:”male”},{sort:[['name', 1]],skip:pageNum*(page-1), limit:pageNum}).toArray(callback(err, data){}) ;
同时查询的时候可以通过$in,$gt,$lt等方式来确定selector的范围。

$ne:不等于;
personCollection.find({age:{$ne:'2'}},function(error,result){}
$in:某值是否在此指定的范围,后面一般指定一个范围数组,数组里面值的类型可以不相同;
personCollection.find({age:{$in:['2','3','4','5']}},function(error,result){}
$nin:表示不在某个数组范围里;
personCollection.find({age:{$lte:'3'}},function(error,result){}
$lt,、$lte、$gt、$gte:分别代表 , >=,它们是用来设置查询范围;
$or:也是指定一个范围来使用,但与上面最大的差别在于,$in 、$nin 有且只有一个数组范围,而 $or 则可以是多个数组范围内满足条件;
personCollection.find({$or:[{name:'王二小'},{age:'2'}]},function(error,result){}

5、更新

有两点要注意:

[1]、update方法如果是要更新文档中的一个或几个属性的时候,必须要用形如{$set:{age:33}}的形式,如果写成{age:33}的形式,则这个文档的其他内容都会被删除,只剩{age:32}这一个属性。
[2]、update方法默认是只更新找到的第一个文档,如果需要所有的文档都更新,则需要在option部分再加上{multi:true},如果想要在查找不到这条记录的时候新增一条,则要在option部分加上{upsert:true}。
person.update({“name”:”jobs”}, {$set{“age”:33}}, {multi:true}, callback(err))
[3]、$inc按步长增加,比如给 age 字段增加1。
personCollection.findAndModify({_id:'1111111'},[],{$inc:{age:1}},{new:true,upset:true},function(error,result){}

6、删除

person.remove({“name”:”jobs”},callback(err){});

7、selector中使用MongoDB自动生成的_id

MongoDB会为每一个文档生成一个_id属性,类似于MySQL的主键,是唯一的。_id的类型是mongoDB自己定义的objectID类型,因此尽管在查询的时候可以得到一个12位或者24位的_id字符串,但是如果想在selector里面通过_id进行查找或其他操作的时候,必须要先通过db.collection.id()方法进行类型转换。
person.remove({“_id”:person.id(stringID)}, callback(err){});

8、mongoDB对文档内的数组进行操作(通过update方法)

[1]、通过$addToSet方法向数组中插入记录,插入前该方法会先查找是否存在这条记录,如果存在则不插入;如果想要插入重复的值,则可以通过$push进行添加。
person.update({“name”:”jobs”}, {$addToSet: {
company: {
name: “google”,
address: USA,
workingTime: 3
}
}, function(err){});

[2]、修改数组中的数据:通过$符。如果在数组中查询的时候要匹配两个属性,必须要使用$elemMatch方法,如果只通过{"name":”google”, "address":USA}去查找,会选择到所有name为google或者address为USA的元素。在定位到这个元素之后,通过$来选定它进行修改。
person.update({
“name”:”jobs”,
company:{$elemMatch:{"name":”google”, "address":USA}}
}, {$set:{"company.$.workingTime":4}},function(){})

[3]、删除数组中指定的数据:通过$pull方法
person.update({
“name”:”jobs”,
},{$pull:{company:{“name”:”google”, “address”:”USA”}}},function(err){})

$pop:删除数组头部或者尾部删除一个值 {$pop:{filed:-1}} 从头删除, {$pop:{filed:1}} 从尾部删除。
personCollection.findAndModify({_id:'1111111'},[],{$pop:{tag:-1}},{new:true,upset:true},function(error,result){}

参考资料

http://jysperm.me/technology/1575
http://www.cppblog.com/dead-horse/archive/2011/09/23/156617.html

https://github.com/kissjs/node-mongoskin 

文档信息

  • 版权声明:自由转载-非商用-非衍生-保持署名 | Creative Commons BY-NC-ND 3.0
    • 原文网址:http://blog.csdn.net/cdztop/article/details/31324027
      • 最后修改时间:2014年06月16日 06:32
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
MySQL's Place: Databases and ProgrammingMySQL's Place: Databases and ProgrammingApr 13, 2025 am 12:18 AM

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

MySQL: From Small Businesses to Large EnterprisesMySQL: From Small Businesses to Large EnterprisesApr 13, 2025 am 12:17 AM

MySQL is suitable for small and large enterprises. 1) Small businesses can use MySQL for basic data management, such as storing customer information. 2) Large enterprises can use MySQL to process massive data and complex business logic to optimize query performance and transaction processing.

What are phantom reads and how does InnoDB prevent them (Next-Key Locking)?What are phantom reads and how does InnoDB prevent them (Next-Key Locking)?Apr 13, 2025 am 12:16 AM

InnoDB effectively prevents phantom reading through Next-KeyLocking mechanism. 1) Next-KeyLocking combines row lock and gap lock to lock records and their gaps to prevent new records from being inserted. 2) In practical applications, by optimizing query and adjusting isolation levels, lock competition can be reduced and concurrency performance can be improved.

MySQL: Not a Programming Language, But...MySQL: Not a Programming Language, But...Apr 13, 2025 am 12:03 AM

MySQL is not a programming language, but its query language SQL has the characteristics of a programming language: 1. SQL supports conditional judgment, loops and variable operations; 2. Through stored procedures, triggers and functions, users can perform complex logical operations in the database.

MySQL: An Introduction to the World's Most Popular DatabaseMySQL: An Introduction to the World's Most Popular DatabaseApr 12, 2025 am 12:18 AM

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.

The Importance of MySQL: Data Storage and ManagementThe Importance of MySQL: Data Storage and ManagementApr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system suitable for data storage, management, query and security. 1. It supports a variety of operating systems and is widely used in Web applications and other fields. 2. Through the client-server architecture and different storage engines, MySQL processes data efficiently. 3. Basic usage includes creating databases and tables, inserting, querying and updating data. 4. Advanced usage involves complex queries and stored procedures. 5. Common errors can be debugged through the EXPLAIN statement. 6. Performance optimization includes the rational use of indexes and optimized query statements.

Why Use MySQL? Benefits and AdvantagesWhy Use MySQL? Benefits and AdvantagesApr 12, 2025 am 12:17 AM

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.

Describe InnoDB locking mechanisms (shared locks, exclusive locks, intention locks, record locks, gap locks, next-key locks).Describe InnoDB locking mechanisms (shared locks, exclusive locks, intention locks, record locks, gap locks, next-key locks).Apr 12, 2025 am 12:16 AM

InnoDB's lock mechanisms include shared locks, exclusive locks, intention locks, record locks, gap locks and next key locks. 1. Shared lock allows transactions to read data without preventing other transactions from reading. 2. Exclusive lock prevents other transactions from reading and modifying data. 3. Intention lock optimizes lock efficiency. 4. Record lock lock index record. 5. Gap lock locks index recording gap. 6. The next key lock is a combination of record lock and gap lock to ensure data consistency.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),