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. Convert Sorted List to Binary Search Tree

    Given a singly linked list where elements are sorted in ascending order, convert it to a height bala ...

  2. ASP.NET MVC - 创建Internet 应用程序

    为了学习 ASP.NET MVC,我们将构建一个 Internet 应用程序. 第 1 部分:创建应用程序. 我们将构建什么 我们将构建一个支持添加.编辑.删除和列出数据库存储信息的 Internet ...

  3. YOLO: Real-Time Object Detection

    YOLO detection darknet框架使用 YOLO 训练自己的数据步骤,宁广涵详细步骤说明

  4. Apache配置手札

    一.绑定域名到子目录 在httpd.conf文件末尾添加 #不同的域名对应到的目录 <VirtualHost *:80> DocumentRoot "D:\wamp\www\ba ...

  5. [转]Java线程安全总结

    最近想将java基础的一些东西都整理整理,写下来,这是对知识的总结,也是一种乐趣.已经拟好了提纲,大概分为这几个主题: java线程安全,java垃圾收集,java并发包详细介绍,java profi ...

  6. centos

    CentOS(Community Enterprise Operating System,中文意思是:社区企业操作系统)是Linux发行版之一,它是来自于Red Hat Enterprise Linu ...

  7. 1323 union解题报告

    http://codeup.cn/problem.php?id=1323 1323: 算法2-1:集合union 时间限制: 1 Sec 内存限制: 32 MB 提交: 2884 解决: 688 题目 ...

  8. 使用Extjs组件实现Top-Left-Main布局并且增加事件响应

    每次在毕业答辩会上,看到同专业的同学只要是XXX管理系统,就是下图所示的界面,看来这中布局还是很受欢迎的(偷笑).接下来进入我们正题,在web项目无论是前端还是后台管理比较常见的布局就是Top-Lef ...

  9. iOS 如何打开后灯(闪光灯)

    - (void)torchOnOrOff { AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMedia ...

  10. SHOI2016游记&滚粗记&酱油记

    Day0 学校刚期中考完,全科血崩,感觉这次真要考不到一本线了tat 晚上写了个可持久化trie的题,也懒得敲板子(上个礼拜都敲过了),就碎叫了 Day1 上午起床吃饭水群看球,吃完中饭就去考场了. ...