nodejs中使用mongodb quickstart
nodejs中使用mongodb quickstart
node 中使用mongodb的quick start.整理的官网crud简单例子.
在百度找了几篇帖子都有问题,所以直接看官网了.
连接MondoDB
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
// Connection URL
var url = 'mongodb://localhost:27017/myproject';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected successfully to server");
db.close();
});
新建数据
使用insertMany新建数据.mongodb中没有关系数据库中行的概念,最相近的概念是document.
var insertDocuments = function(db, callback) {
// Get the documents collection
var collection = db.collection('documents');
// Insert some documents
collection.insertMany([
{a : 1}, {a : 2}, {a : 3}
], function(err, result) {
assert.equal(err, null);
assert.equal(3, result.result.n);
assert.equal(3, result.ops.length);
console.log("Inserted 3 documents into the collection");
callback(result);
});
}
The insert command returns an object with the following fields:
- result Contains the result document from MongoDB
- ops Contains the documents inserted with added _id fields
- connection Contains the connection used to perform the insert
建立连接后调用
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
// Connection URL
var url = 'mongodb://localhost:27017/myproject';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected successfully to server");
insertDocuments(db, function() {
db.close();
});
});
读取collection中的数据
var findDocuments = function(db, callback) {
// Get the documents collection
var collection = db.collection('documents');
// Find some documents
collection.find({}).toArray(function(err, docs) {
assert.equal(err, null);
console.log("Found the following records");
console.log(docs)
callback(docs);
});
}
这样会查询collection中的全部数据.我们把dindDocuments添加到MongoClient.connect的回调中
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
// Connection URL
var url = 'mongodb://localhost:27017/myproject';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected correctly to server");
insertDocuments(db, function() {
findDocuments(db, function() {
db.close();
});
});
});
是的,collection.find是可以指定查询条件的
var findDocuments = function(db, callback) {
// Get the documents collection
var collection = db.collection('documents');
// Find some documents
collection.find({'a': 3}).toArray(function(err, docs) {
assert.equal(err, null);
console.log("Found the following records");
console.log(docs);
callback(docs);
});
}
更新数据
使用updateOne进行单(document,不是行)数据的更新
var updateDocument = function(db, callback) {
// Get the documents collection
var collection = db.collection('documents');
// Update document where a is 2, set b equal to 1
collection.updateOne({ a : 2 }
, { $set: { b : 1 } }, function(err, result) {
assert.equal(err, null);
assert.equal(1, result.result.n);
console.log("Updated the document with the field a equal to 2");
callback(result);
});
}
加入MongoClient.connect的回调看结果:
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
// Connection URL
var url = 'mongodb://localhost:27017/myproject';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected successfully to server");
insertDocuments(db, function() {
updateDocument(db, function() {
db.close();
});
});
});
删除document
类似查询的方式使用deleteOne删除document
var removeDocument = function(db, callback) {
// Get the documents collection
var collection = db.collection('documents');
// Insert some documents
collection.deleteOne({ a : 3 }, function(err, result) {
assert.equal(err, null);
assert.equal(1, result.result.n);
console.log("Removed the document with the field a equal to 3");
callback(result);
});
}
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
// Connection URL
var url = 'mongodb://localhost:27017/myproject';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected successfully to server");
insertDocuments(db, function() {
updateDocument(db, function() {
removeDocument(db, function() {
db.close();
});
});
});
});
添加索引
跟关系数据库一样添加索引可以提高查询效率
var indexCollection = function(db, callback) {
db.collection('documents').createIndex(
{ "a": 1 },
null,
function(err, results) {
console.log(results);
callback();
}
);
};
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
// Connection URL
var url = 'mongodb://localhost:27017/myproject';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected successfully to server");
insertDocuments(db, function() {
indexCollection(db, function() {
db.close();
});
});
});
原文地址: http://mongodb.github.io/node-mongodb-native/2.2/quick-start/
nodejs中使用mongodb quickstart的更多相关文章
- nodejs中使用mongodb
/** * 使用mongodb存储数据 * 1 首先安装mongodb nodejs插件 npm install mongodb --save-dev * 2 安装express (非必须) * * ...
- nodejs中连接mongodb数据库
const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/blog', { useNewUrlParser ...
- Nodejs中Mongodb使用
Mongodb使用 打开解压后的Mongodb文件夹,新建data.logs文件夹,并在logs文件夹中新建mongodb.log文档. 添加后Mongod文件夹示意图: 用cmd命令行启动Mongo ...
- mongodb replica set 和 nodejs中使用mongoose连接replica
一.mongodb replication 介绍 官网上的第一句话就是Replication is the process of synchronizing data across multiple ...
- Spring Boot中使用MongoDB数据库
前段时间分享了关于Spring Boot中使用Redis的文章,除了Redis之后,我们在互联网产品中还经常会用到另外一款著名的NoSQL数据库MongoDB. 下面就来简单介绍一下MongoDB,并 ...
- nodejs中获取时间戳、时间差
Nodejs中获取时间戳的方法有很多种,例如: new Date().getTime() Date.now() process.uptime() process.hrtime() 平时想获取一个时间戳 ...
- 在Nodejs中如何调用C#的代码
最近需要在Nodejs中用到C#的代码,从网上了解到可以采用Edgejs来实现Nodejs与C#的代码交互, 直接复制网上的代码运行总是出各种错,填了不少坑,现在把自己的案例代码大致整理一下,方便以后 ...
- nodejs 中自定义事件
经常看到 req.on('error', function(){...}); 这种代码. 在nodejs中,可以使用 EventEmitter来实现. 具体的关键词有如下几个: var reqEven ...
- NodeJS中的异步I/O、事件驱动
nodejs的主要特点是单线程.异步I/O.事件驱动.让我们先大概了解一下这些名词的意思. 单线程 单线程是任务按照顺序执行的,并且每次只执行一个任务,只有前面的任务执行完成以后,后面的任务才执行.在 ...
随机推荐
- VirtualBox“切换到无缝模式”和“自动调整显示尺寸”菜单无法使用
现象:VirtualBox“切换到无缝模式”和“自动调整显示尺寸”菜单无法使能,无法全窗口显示虚拟机桌面,菜单状态如下图所示: 原因:该功能的支持需要安装VirtualBox增强功能 方法:安装Vir ...
- python 的None 探究
a = None b = None print id(a),id(b),id(None) # 9430224 9430224 9430224 可能在别的环境下运行不是这个数,但是这三个数应该是一样的. ...
- form表单重置、清空方法记录
myform 是form的id属性值 1.调用reset()方法 function fomrReset() { document.getElementById("myform"). ...
- Baidu URL的部分参数
[Baidu URL的部分参数] 1.Baidu Form表单如下: 2.部分参数解析 wd 查询关键字,就是你要搜索的内容. bs 上一次搜索的词或者内容: rn 搜索结果页每页显示的数目,默认 ...
- ECMAScript6新特性之Array API
一 填充数组 var arr = new Array(5); arr.fill('abc',2,4); console.log('Array.prototype.fill',arr); // [und ...
- VMware克隆CentOS网络配置
配置网络 如果是克隆CentOS的: vi /etc/udev/rules.d/70-persistent-net.rules 注释掉网络eth0,把最后一个改为eth0,记录下mac地址. vi / ...
- 【校招面试 之 C/C++】第16题 C++ new和delete的实现原理
1.new new操作针对数据类型的处理,分为两种情况: (1)简单数据类型(包括基本数据类型和不需要构造函数的类型) 代码实例: int* p = new int; 汇编码如下: int* p = ...
- OC 线程操作2 - NSThread
方法1 :直接创建 alloc init - (void)createNSThread111{ /* 参数1: (nonnull id) 目标对象 self 参数2:(nonnull SEL) ...
- OC - GCD 队列组 - 下载图片画图
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{ [self downloadIma ...
- linux下安装memcached以及扩展(xampp环境)
网上有很多相关的文章,就不具体写了.(假设这里文件都上传到更目录下的tmp文件夹下) 1.大致流程先装 libevent 和 memcache http://www.cnblogs.com/zgx/a ...