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(& ...
随机推荐
- Linux Linux程序练习十九
题目:编写一个同步服务器模型 要求: )客户端A主机给服务器B主机发送报文, )B服务器主机收到报文以后同时分发给C1主机.C2主机: )C1主机和C2主机打印出客户端A的报文 bug总结:本来这道题 ...
- Autofac手动注入及自动注入示例
参考:http://www.cnblogs.com/xinchuang/archive/2013/05/07/3065433.html#2911661 一.环境 vs2012.mvc4..Net Fr ...
- Error: Could not find the required version of the Java(TM) 2 Runtime Environment in'(null)'.
今天拿到一台新机器,搭一下开发环境,安装个JDK是个很基本的事情,从Orale的网站上下了个安装,但是一直出下面的错: 我信了你的邪,Google了一圈,有人说是可能文件下载有问题,重新下载安装就可以 ...
- Golang友团无闻Go语言Web基础视频教程
教程内容:GO语言资料Golang友团无闻Go语言编程基础Golang友团无闻Go语言Web基础教程 Go语言Web基础教程列表:[Go Web基础]12Go Web 扩展学习.mp4[Go Web基 ...
- input 禁止输入法
<INPUT TYPE = text STYLE = "ime-mode:disabled" > 即可禁止输入法 js形式: active 代表输入法为中文inacti ...
- Javascript最简单的把html字符串编码的方法
html字符串是指’<div id=”a”>aklsdjfklsjdfl</div>’这样的带html特殊符号的字符串,我们通常要对他进行处理再输出以免输出成了真正的html元 ...
- php $CI =& get_instance();
初学php 看有人这样写,$CI =& get_instance(); 要你自定义的类库中访问CodeIgniter的原始资源,你必须使用 get_instance() 函数.这个函数返回一个 ...
- 招聘前端、Java后端开发、测试、Mysql DBA
公司介绍: http://www.lagou.com/gongsi/43095.html http://www.yamichu.com 简历发到: zhuye@yamichu.com 招聘职位: JA ...
- Spring配置文件中别名的使用
id是bean的唯一标识符号,若没有Id那么name为默认标识符号 如果配置了id又配置了name,那么name为别名,别名可以配置多个,这些别名用逗号.空格等隔开. 还可以通过<alias n ...
- js鼠标事件大全
一般事件 事件 浏览器支持 描述 onClick HTML: 2 | 3 | 3.2 | 4 Browser: IE3 | N2 | O3 鼠标点击事件,多用在某个对象控制的范围内的鼠标点击 onDb ...