3.从Node.js操作MongoDB文档
1.更新文档结构,而非SQL
2.数据库更新运算符
在MongoDB中执行对象的更新时,需要确切的指定需要改变什么字段。需要如何改变。不像SQL语句建立冗长的查询字符串来定义更新。
MongoDB中可以实现update对象与运算符定义如何改变文档中的数据
{
<operator>:{<field_operation>,<field_operation>,...},
<operator>:{<field_operation>,<field_operation>,...}
...
}
{
name:'myName',
countA:0,
countB:0,
days:["Monday","Wednesday"],
scores:[{id:"test1",score:94},{id:"test2",score:85},{id:"test3",score:97}]
}
//进行update
{
$inc:{countA:5,countB:1},
$set:{name:"New Name"},
$sort:{score:1}
}
3.将文档添加到集合
用MongoDB的数据库进行交互的另一个常见任务是往集合中插入文档。
要插入一个文档,首先是创建JavaScript对象表示要存储的文档。因为MongoDB使用的BSON格式是基于JavaScript符号的,再此创建一个JavaScript对象。
insert(docs,[options],callback)
把文档插入到集合。
var MongoClient=require('mongodb').MongoClient;
function addObject(collection,object){
collection.insert(object,function(err,result){
if(!err){
console.log('Insert : ');
console.log(result);
}
});
}
MongoClient.connect("mongodb://localhost/",function(err,db){
var myDB=db.db("astro");
myDB.dropCollection("nebulae");
myDB.createCollection("nebulae",function(err,nebulae){
addObject(nebulae,{ngc:"NGC 10001",name:"Helix",type:"planetary",location:"Aquila"});
addObject(nebulae,{ngc:"NGC 20001",name:"Cat's Eye",type:"planetary",location:"Draco"});
})
setTimeout(function(){db.close();console.log('db closed')},3000)
})
4.从集合获取文档
对于存储在MongoDB数据库中的数据,通常需要执行:检索一个或多个文档。
如:商业网站上的产品的产品信息,信息被储存一次但检索多次(筛选,排序,汇总)
find(query,[options],callback)
findOne(query,[options],callback)
query对象包含了与文档的字段匹配的属性。与query对象匹配的文档包含在列表中。
options参数是一个对象,指定有关查找文档(限制,排序和返回值)
不同之处是回调函数:find()方法返回一个可在检索的文档上迭代的Cursor对象。findOne()返回单个对象。
利用find()和findOne(),在MongoDB中查找文档
var MongoClient=require('mongodb').MongoClient;
MongoClient.connect("mongodb://localhost/",function(err,db){
var myDB=db.db("astro");
myDB.collection("nebulae",function(err,nebulae){
nebulae.find(function(err,items){
items.toArray(function(err,itemArr){
console.log('Document Array: ');
console.log(itemArr);
});
});
nebulae.find(function(arr,items){
items.each(function(err,item){
if(item){
console.log('singular document');
console.log(item);
}
})
});
nebulae.findOne({name:'Helix'},function(err,item){
console.log('found one: ');
console.log(item);
})
})
setTimeout(function(){db.close();console.log('close db');},3000);
})
更新集合中的文档
update(query,update,[options],[callback])
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect("mongodb://localhost/", function(err, db) {
var myDB = db.db("astro");
myDB.collection("nebulae", function(err, nebulae) {
nebulae.find({ type: "planetary" }, function(err, items) {
items.toArray(function(err, itemArr) {
console.log("before update: ");
console.log(itemArr);
nebulae.update({ type: "planetary", $isolated: 1 },
{ $set: { type: "Plane", update: true }},
{ upsert: false, multi: true, w: 1 },
function(err, results) {
nebulae.find({type:"Plane"}).toArray(function(err, docs) {
console.log("after update: ");
console.log(docs);
db.close();
});
}
)
})
})
})
})
原子地修改文档的集合
findAndModify(query,sort,update,[options],callback)
var MongoClient=require('mongodb').MongoClient;
MongoClient.connect("mongodb://localhost/",function(err,db){
var myDB=db.db('astro');
myDB.collection("nebulae",function(err,nebulae){
nebulae.find({name:"Helix"},function(err,items){
items.toArray(function(err,itemArr){
console.log("before modify: ");
console.log(itemArr);
nebulae.findAndModify({location:"Draco"},[['name',1]],
{$set:{location:'Draco_FF',"update":true}},
{w:1,new:true},function(err,doc){
console.log('after modify: ');
console.log(doc);
db.close();
}
)
})
})
})
})
保存集合中的文档
save(doc,[options],[callback])
var MongoClient=require('mongodb').MongoClient;
MongoClient.connect("mongodb://localhost/",function(err,db){
var myDB=db.db('astro');
myDB.collection("nebulae",function(err,nebulae){
nebulae.findOne({type:"Plane"},function(err,item){
console.log("before save: ");
console.log(item);
item.info="some New Info";
nebulae.save(item,{w:1},function(err,results){
nebulae.findOne({_id:item._id},function(err,savedItem){
console.log("after saved: ");
console.log(savedItem);
db.close();
})
})
})
})
})
使用upsert往集合中插入文档
var MongoClient=require('mongodb').MongoClient;
MongoClient.connect("mongodb://localhost/",function(err,db){
var myDB=db.db("astro");
myDB.collection("nebulae",function(err,nebulae){
nebulae.find({type:"diffuse"},function(err,items){
items.toArray(function(err,itemArr){
console.log("before upsert: ");
console.log(itemArr);
nebulae.update({type:"diffuse"},
{$set:{ngc:"NGC 3372",name:"Carina",type:"diffuse",location:"Carina"}},
{upsert:true,w:1,forceServerObjectId:false},
function(err,results){
nebulae.find({type:"diffuse"},function(err,items){
items.toArray(function(err,itemArr){
console.log('after upsert 1: ');
console.log(itemArr);
var itemID=itemArr[0]._id;
nebulae.update({_id:itemID},
{$set: {ngc:"NGC 3373",name:"Carina",type:"Diffuse",location:"Carina"}},
{update:true,w:1},
function(err,results){
nebulae.findOne({_id:itemID},function(err,item){
console.log('after upsert 2: ');
console.log(item);
db.close();
})
}
)
})
})
}
)
})
})
})
})
从集合中删除文档
remove([query],[options],[callback])
var MongoClient=require('mongodb').MongoClient;
MongoClient.connect("mongodb://localhost/",function(err,db){
var myDB=db.db("astro");
myDB.collection("nebulae",function(err,nebulae){
nebulae.find(function(err,items){
items.toArray(function(err,itemArr){
console.log('before delete: ');
console.log(itemArr);
nebulae.remove({type:"Diffuse"},function(err,results){
console.log('delete: '+results+" document.");
nebulae.find(function(err,items){
items.toArray(function(err,itemArr){
console.log('after delete: ');
console.log(itemArr);
db.close();
})
})
})
})
})
})
})
从集合中删除单个文档
findAndRemove(query,sort,[options],callback)
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect("mongodb://localhost/", function(err, db) {
var myDB = db.db("astro");
myDB.collection("nebulae", function(err, nebulae) {
nebulae.find().toArray(function(err, docs) {
console.log("before delete: ");
console.log(docs);
nebulae.findAndRemove({ type: "Diffuse" }, [
['name',1]
], { w: 1 }, function(err, results) {
console.log('deleted:\n' + results);
nebulae.find().toArray(function(err, itemArr) {
console.log('after delete: ');
console.log(itemArr);
db.close();
})
})
})
})
})
...
3.从Node.js操作MongoDB文档的更多相关文章
- Node.js 操作Mongodb
Node.js 操作Mongodb1.简介官网英文文档 https://docs.mongodb.com/manual/ 这里几乎什么都有了MongoDB is open-source docum ...
- js介绍,js三种引入方式,js选择器,js四种调试方式,js操作页面文档DOM(修改文本,修改css样式,修改属性)
js介绍 js运行编写在浏览器上的脚本语言(外挂,具有逻辑性) 脚本语言:运行在浏览器上的独立的代码块(具有逻辑性) 操作BOM 浏览器对象盒子 操作DOM 文本对象 js三种引入方式 (1)行间式: ...
- node.js零基础详细教程(7):node.js操作mongodb,及操作方法的封装
第七章 建议学习时间4小时 课程共10章 学习方式:详细阅读,并手动实现相关代码 学习目标:此教程将教会大家 安装Node.搭建服务器.express.mysql.mongodb.编写后台业务逻辑. ...
- node.js操作mongoDB数据库
链接数据库: var mongo=require("mongodb"); var host="localhost"; var port=mongo.Connec ...
- 87.node.js操作mongoDB数据库示例分享
转自:https://www.cnblogs.com/mracale/p/5845148.html 连接数据库 var mongo=require("mongodb"); va ...
- js操作document文档元素 节点交换交换
<input type="text" value="1" id='text1'> <input type="text" v ...
- node.js操作数据库之MongoDB+mongoose篇
前言 node.js的出现,使得用前端语法(javascript)开发后台服务成为可能,越来越多的前端因此因此接触后端,甚至转向全栈发展.后端开发少不了数据库的操作.MongoDB是一个基于分布式文件 ...
- [Node.js]连接mongodb
摘要 前面介绍了node.js操作mysql以及redis的内容,这里继续学习操作mongodb的内容. 安装驱动 安装命令 cnpm install mongodb 安装成功 数据库操作 因为mon ...
- Node.js 中MongoDB的基本接口操作
Node.js 中MongoDB的基本接口操作 连接数据库 安装mongodb模块 导入mongodb模块 调用connect方法 文档的增删改查操作 插入文档 方法: db.collection(& ...
随机推荐
- [No00007F]2016-面经[下] 英文简历写作技巧
一.简历种类 1.中式 中式简历中,常包括政治面貌,性格及身高体重等.如果中英文简历一起递交,建议中文不写政治面貌,因为如果去外企工作,背景中的政治色彩越少越好,起码没有必要让老外知道. 性格是一个主 ...
- Permutation test: p, CI, CI of P 置换检验相关统计量的计算
For research purpose, I've read a lot materials on permutation test issue. Here is a summary. Should ...
- 关于Oracle AUTONOMOUS TRANSACTION(自治事务)的介绍
AUTONOMOUS TRANSACTION(自治事务)的介绍 在基于低版本的ORACLE做一些项目的过程中,有时会遇到一些头疼的问题,比如想在执行当前一个由多个DML组成的transaction(事 ...
- flask+sqlite3+echarts3 系统监控
总的而言,分三部分: 1.监控器(monitor.py): 每秒获取系统的四个cpu的使用率,存入数据库. 2.路由器(app.py): 响应页面的ajax,获取最新的一条或多条数据. 3.页面(in ...
- 【IIS】IIS6.1配置 *.config 文件 的MIME类型用于升级程序
参考:http://blog.csdn.net 1. 2. 请求筛选中允许config文件下载, 3. 添加.config到 MIME类型. 3.注意:筛选项.
- 【转】通过自定义的URL Scheme启动你的App
http://blog.csdn.net/ba_jie/article/details/6884818原文地址:http://iphonedevelopertips.com/cocoa/launchi ...
- 用 CSS 隐藏页面元素
用 CSS 隐藏页面元素有许多种方法.你可以将 opacity 设为 0 将 visibility 设为 hidden 将 display 设为 none 将 position 设为 absolute ...
- COGS439. [网络流24题] 软件补丁
[问题描述] 对于一个软件公司来说,在发行一个新软件之后,可以说已经完成了工作.但是实际上,许多软件公司在发行一个新产品之后,还经常发送补丁程序,修改原产品中的错误(当然,有些补丁是要收费的). 如某 ...
- fedora22命令useradd,groupadd等命令不能自动补全
sudo ls -l /sbin/useradd 发现登陆账户没有读权限 修改为其他账户为读权限即可
- RabbitMQ consumer的一些坑
坑 坑就像是恶梦,总是在最不设防的时候出现,打的你满地找牙.这里记录一些坑,遇到的朋友可以及时的跳出,避免带来损失. 使用事件方式去获取queue中的消息,然后再进行处理.这看起来没什么问题,但是如果 ...