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文档的更多相关文章

  1. Node.js 操作Mongodb

    Node.js 操作Mongodb1.简介官网英文文档  https://docs.mongodb.com/manual/  这里几乎什么都有了MongoDB is open-source docum ...

  2. js介绍,js三种引入方式,js选择器,js四种调试方式,js操作页面文档DOM(修改文本,修改css样式,修改属性)

    js介绍 js运行编写在浏览器上的脚本语言(外挂,具有逻辑性) 脚本语言:运行在浏览器上的独立的代码块(具有逻辑性) 操作BOM 浏览器对象盒子 操作DOM 文本对象 js三种引入方式 (1)行间式: ...

  3. node.js零基础详细教程(7):node.js操作mongodb,及操作方法的封装

    第七章 建议学习时间4小时  课程共10章 学习方式:详细阅读,并手动实现相关代码 学习目标:此教程将教会大家 安装Node.搭建服务器.express.mysql.mongodb.编写后台业务逻辑. ...

  4. node.js操作mongoDB数据库

    链接数据库: var mongo=require("mongodb"); var host="localhost"; var port=mongo.Connec ...

  5. 87.node.js操作mongoDB数据库示例分享

    转自:https://www.cnblogs.com/mracale/p/5845148.html 连接数据库   var mongo=require("mongodb"); va ...

  6. js操作document文档元素 节点交换交换

    <input type="text" value="1" id='text1'> <input type="text" v ...

  7. node.js操作数据库之MongoDB+mongoose篇

    前言 node.js的出现,使得用前端语法(javascript)开发后台服务成为可能,越来越多的前端因此因此接触后端,甚至转向全栈发展.后端开发少不了数据库的操作.MongoDB是一个基于分布式文件 ...

  8. [Node.js]连接mongodb

    摘要 前面介绍了node.js操作mysql以及redis的内容,这里继续学习操作mongodb的内容. 安装驱动 安装命令 cnpm install mongodb 安装成功 数据库操作 因为mon ...

  9. Node.js 中MongoDB的基本接口操作

    Node.js 中MongoDB的基本接口操作 连接数据库 安装mongodb模块 导入mongodb模块 调用connect方法 文档的增删改查操作 插入文档 方法: db.collection(& ...

随机推荐

  1. ubuntu系统升级记录

    之前在openstack中安装了ubuntu 12.04虚拟机,版本较低,需要升级为高版本.下面分享下升级过程: ubuntu系统升级操作:$ cat /etc/issueUbuntu 12.04.5 ...

  2. Android5.0资源 colorAccent,colorPrimary,colorPrimaryDark

  3. EF7 使用 K EF 异常

    在使用EF 7 Code first功能时. k ef 报如下错误: 解决办法: 在project.json 同级目录下新建k.cmd,内容如下: "%~dp0approot\runtime ...

  4. 详解 Android Activity 生命周期

    从以下几个方面详细说一下Activity的生命周期: 1.回到主屏幕再打开和退出程序的时候. 2.屏幕旋转的时候. 3.打开其它的Activity的情况. 4.打开一个Layou透明的Activity ...

  5. HTML5之API

    HTML5就是牛,可以直接播放音视频,还可以作图: 一.HTML5中播放视频和音频: 加载时直接播放音频的方式:new Audio("BY2.mp3").play(); <d ...

  6. 常见排序java实现

    public class Sort { public static void main(String[] args) { int[] data = {49,38,65,97,76,13,27,49}; ...

  7. 解决:MIUI 8应用商店下载不了软件 APP

    MIUI 8应用商店下载不了软件,是什么原因呢? 原因是:刷了国际版的MIUI,然后又刷回国内的MIUI,刷机时数据没有清理干净. 解决办法:使用RE管理器或者其他第三方可以编辑系统文件的文件管理器, ...

  8. oracle误删表解决方案

    ·delete(删除一条记录)·drop或truncate删除表格中数据 1.delete误删除的解决方法原理:利用oracle提供的闪回方法,如果在删除数据后还没做大量的操作(只要保证被删除数据的块 ...

  9. Python Day7

    概述 面向对象高级语法部分 静态方法.类方法.属性方法 类的特殊方法 反射 静态方法 通过@staticmethod装饰器即可把其装饰的方法变为一个静态方法,什么是静态方法呢?其实不难理解,普通的方法 ...

  10. linux下常见解压缩命令

    linux下常见的压缩文件格式有tar.gz.tar.gz.tar.bz2.zip等等.对于不同的压缩文件格式有对应的解压缩命令.下面就对此小结一下: 1.后缀为.tar 用 tar –xvf 解压 ...