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(& ...
随机推荐
- sql 首写字母查询姓名(字段)
来自网上大神,不知道是谁,挂不上链接 /////////////////////// 1.生成方法函数 create function f_GetPy(@str nvarchar(4000)) ret ...
- Dubbo消费端错误: ClassNotFoundException: org.apache.zookeeper.proto.WatcherEvent
出现错误的原因是消费端war没有启动成功, 但是zkClient和Dubbo的对应Thread启动了, web container无法加载对应的类, INFO: Initializing Protoc ...
- [转载]一张图看懂开源许可协议,开源许可证GPL、BSD、MIT、Mozilla、Apache和LGPL的区别
本文转载自:http://blog.csdn.net/testcs_dn/article/details/38496107 开源许可证GPL.BSD.MIT.Mozilla.Apache和LGPL的区 ...
- [Google Guava]字符串处理:连接器、拆分器、字符匹配器
一.连接器[Joiner] 二.拆分器[Splitter] 三.字符匹配器[CharMatcher] 四.字符集[Charsets] Charsets:针对所有Java平台都要保证支持的六种字符集提供 ...
- iOS 如何打开后灯(闪光灯)
- (void)torchOnOrOff { AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMedia ...
- Google调用explorer.exe打开本地文件
给IE浏览器地址栏输个本地文件路径,会自动用explorer.exe打开,这个挺好的,但是IE对jQuery稍微高点的版本不怎么待见,只好自己给Google折腾一个调用explorer的功能----- ...
- ES6新特性:使用export和import实现模块化
在ES6前, 前端就使用RequireJS或者seaJS实现模块化, requireJS是基于AMD规范的模块化库, 而像seaJS是基于CMD规范的模块化库, 两者都是为了为了推广前端模块化的工 ...
- PyChram中同目录下import引包报错的解决办法?
相信很多同学和我一样在PyChram工具中新建python项目的同目录下import引包会报错提示找不到,这是因为该项目找不到python的环境导致的: 如果文件开始的时候包引包的错误可以,都可以用用 ...
- bzoj4591 【Shoi2015】超能粒子炮·改
由Lucas定理C(n,k)=C(n/2333,k/2333)*C(n%2333,k%2333)%2333 则ans=ΣC(n,i),(i<=k) =C(n/2333,0)*C(n%2333, ...
- codevs 2988 保留小数 2
2988 保留小数 2 时间限制: 1 s 空间限制: 128000 KB 题目等级 : 白银 Silver 题目描述 Description 这个难度是吸引你点进来的.(其实难度挺 ...