Table of Contents
特点
无模式
异步写入
简单查询
无需运维
安装和备份
设计文档结构
ObjectID
查询和更新
查询操作符
更新操作符
聚合查询(Aggregation)
查询命令还有几个选项
1、数据库连接
2、索引
3、新建/增加数据
4、查询
5、更新
6、删除
7、selector中使用MongoDB自动生成的_id
8、mongoDB对文档内的数组进行操作(通过update方法)
参考资料
Home Database Mysql Tutorial MongoDB+node-mongoskin学习笔记

MongoDB+node-mongoskin学习笔记

Jun 07, 2016 pm 03:57 PM
study notes

特点 无模式 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 of this Website
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

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)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to delete Xiaohongshu notes How to delete Xiaohongshu notes Mar 21, 2024 pm 08:12 PM

How to delete Xiaohongshu notes? Notes can be edited in the Xiaohongshu APP. Most users don’t know how to delete Xiaohongshu notes. Next, the editor brings users pictures and texts on how to delete Xiaohongshu notes. Tutorial, interested users come and take a look! Xiaohongshu usage tutorial How to delete Xiaohongshu notes 1. First open the Xiaohongshu APP and enter the main page, select [Me] in the lower right corner to enter the special area; 2. Then in the My area, click on the note page shown in the picture below , select the note you want to delete; 3. Enter the note page, click [three dots] in the upper right corner; 4. Finally, the function bar will expand at the bottom, click [Delete] to complete.

Learn to completely uninstall pip and use Python more efficiently Learn to completely uninstall pip and use Python more efficiently Jan 16, 2024 am 09:01 AM

No more need for pip? Come and learn how to uninstall pip effectively! Introduction: pip is one of Python's package management tools, which can easily install, upgrade and uninstall Python packages. However, sometimes we may need to uninstall pip, perhaps because we wish to use another package management tool, or because we need to completely clear the Python environment. This article will explain how to uninstall pip efficiently and provide specific code examples. 1. How to uninstall pip The following will introduce two common methods of uninstalling pip.

What should I do if the notes I posted on Xiaohongshu are missing? What's the reason why the notes it just sent can't be found? What should I do if the notes I posted on Xiaohongshu are missing? What's the reason why the notes it just sent can't be found? Mar 21, 2024 pm 09:30 PM

As a Xiaohongshu user, we have all encountered the situation where published notes suddenly disappeared, which is undoubtedly confusing and worrying. In this case, what should we do? This article will focus on the topic of "What to do if the notes published by Xiaohongshu are missing" and give you a detailed answer. 1. What should I do if the notes published by Xiaohongshu are missing? First, don't panic. If you find that your notes are missing, staying calm is key and don't panic. This may be caused by platform system failure or operational errors. Checking release records is easy. Just open the Xiaohongshu App and click "Me" → "Publish" → "All Publications" to view your own publishing records. Here you can easily find previously published notes. 3.Repost. If found

How to add product links in notes in Xiaohongshu Tutorial on adding product links in notes in Xiaohongshu How to add product links in notes in Xiaohongshu Tutorial on adding product links in notes in Xiaohongshu Mar 12, 2024 am 10:40 AM

How to add product links in notes in Xiaohongshu? In the Xiaohongshu app, users can not only browse various contents but also shop, so there is a lot of content about shopping recommendations and good product sharing in this app. If If you are an expert on this app, you can also share some shopping experiences, find merchants for cooperation, add links in notes, etc. Many people are willing to use this app for shopping, because it is not only convenient, but also has many Experts will make some recommendations. You can browse interesting content and see if there are any clothing products that suit you. Let’s take a look at how to add product links to notes! How to add product links to Xiaohongshu Notes Open the app on the desktop of your mobile phone. Click on the app homepage

A deep dive into matplotlib's colormap A deep dive into matplotlib's colormap Jan 09, 2024 pm 03:51 PM

To learn more about the matplotlib color table, you need specific code examples 1. Introduction matplotlib is a powerful Python drawing library. It provides a rich set of drawing functions and tools that can be used to create various types of charts. The colormap (colormap) is an important concept in matplotlib, which determines the color scheme of the chart. In-depth study of the matplotlib color table will help us better master the drawing functions of matplotlib and make drawings more convenient.

Revealing the appeal of C language: Uncovering the potential of programmers Revealing the appeal of C language: Uncovering the potential of programmers Feb 24, 2024 pm 11:21 PM

The Charm of Learning C Language: Unlocking the Potential of Programmers With the continuous development of technology, computer programming has become a field that has attracted much attention. Among many programming languages, C language has always been loved by programmers. Its simplicity, efficiency and wide application make learning C language the first step for many people to enter the field of programming. This article will discuss the charm of learning C language and how to unlock the potential of programmers by learning C language. First of all, the charm of learning C language lies in its simplicity. Compared with other programming languages, C language

Getting Started with Pygame: Comprehensive Installation and Configuration Tutorial Getting Started with Pygame: Comprehensive Installation and Configuration Tutorial Feb 19, 2024 pm 10:10 PM

Learn Pygame from scratch: complete installation and configuration tutorial, specific code examples required Introduction: Pygame is an open source game development library developed using the Python programming language. It provides a wealth of functions and tools, allowing developers to easily create a variety of type of game. This article will help you learn Pygame from scratch, and provide a complete installation and configuration tutorial, as well as specific code examples to get you started quickly. Part One: Installing Python and Pygame First, make sure you have

Let's learn how to input the root number in Word together Let's learn how to input the root number in Word together Mar 19, 2024 pm 08:52 PM

When editing text content in Word, you sometimes need to enter formula symbols. Some guys don’t know how to input the root number in Word, so Xiaomian asked me to share with my friends a tutorial on how to input the root number in Word. Hope it helps my friends. First, open the Word software on your computer, then open the file you want to edit, and move the cursor to the location where you need to insert the root sign, refer to the picture example below. 2. Select [Insert], and then select [Formula] in the symbol. As shown in the red circle in the picture below: 3. Then select [Insert New Formula] below. As shown in the red circle in the picture below: 4. Select [Radical Formula], and then select the appropriate root sign. As shown in the red circle in the picture below:

See all articles