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

  1. nodejs中使用mongodb

    /** * 使用mongodb存储数据 * 1 首先安装mongodb nodejs插件 npm install mongodb --save-dev * 2 安装express (非必须) * * ...

  2. nodejs中连接mongodb数据库

    const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/blog', { useNewUrlParser ...

  3. Nodejs中Mongodb使用

    Mongodb使用 打开解压后的Mongodb文件夹,新建data.logs文件夹,并在logs文件夹中新建mongodb.log文档. 添加后Mongod文件夹示意图: 用cmd命令行启动Mongo ...

  4. mongodb replica set 和 nodejs中使用mongoose连接replica

    一.mongodb replication 介绍 官网上的第一句话就是Replication is the process of synchronizing data across multiple ...

  5. Spring Boot中使用MongoDB数据库

    前段时间分享了关于Spring Boot中使用Redis的文章,除了Redis之后,我们在互联网产品中还经常会用到另外一款著名的NoSQL数据库MongoDB. 下面就来简单介绍一下MongoDB,并 ...

  6. nodejs中获取时间戳、时间差

    Nodejs中获取时间戳的方法有很多种,例如: new Date().getTime() Date.now() process.uptime() process.hrtime() 平时想获取一个时间戳 ...

  7. 在Nodejs中如何调用C#的代码

    最近需要在Nodejs中用到C#的代码,从网上了解到可以采用Edgejs来实现Nodejs与C#的代码交互, 直接复制网上的代码运行总是出各种错,填了不少坑,现在把自己的案例代码大致整理一下,方便以后 ...

  8. nodejs 中自定义事件

    经常看到 req.on('error', function(){...}); 这种代码. 在nodejs中,可以使用 EventEmitter来实现. 具体的关键词有如下几个: var reqEven ...

  9. NodeJS中的异步I/O、事件驱动

    nodejs的主要特点是单线程.异步I/O.事件驱动.让我们先大概了解一下这些名词的意思. 单线程 单线程是任务按照顺序执行的,并且每次只执行一个任务,只有前面的任务执行完成以后,后面的任务才执行.在 ...

随机推荐

  1. Maven的配置以及IDEA导入本地Maven

    1.首先看你的电脑jdk的环境变量是否配成功 2.Maven的下载地址:http://maven.apache.org/download.cgi 3.下载完成后解压到你要安装的目录,我的是直接放在D: ...

  2. 由于C++类库版本不同导致的OpenCV编译链接错误

    太长不看版:GCC4和GCC5使用的C++标准库下,string的名字不一样,导致链接错误. 之前在Ubuntu下使用OpenCV的时候一切正常.后来再次编译的时候,连接器提示有些库函数找不到: ma ...

  3. Oracle VM VirtualBox做好虚拟硬盘后,如何进一步修改虚拟硬盘的大小

    以管理员身份打开, 命令提示符窗口,然后利用命令cd进入Oracle VM VirtualBox安装目录,如下图: 我进入了Oracle VM VirtualBox安装目录:D:\Program Fi ...

  4. python文件的只读,只写操作

    只读:r rb(bytes类型数据) 只写:w wb(bytes类型数据) 在文件最后追加: f = open('log',mode='a',encoding='utf-8') f.write('这里 ...

  5. show_space查看对象空间使用情况

    CREATE OR REPLACE PROCEDURE show_space(p_segname IN VARCHAR2, p_owner IN VARCHAR2 DEFAULT USER, p_ty ...

  6. Linux下tar.gz 安装

    将安装文件拷贝至你的目录中 如果是以root身份登录上的,就将软件拷贝至/root中. cp xxx.tar.gz /root 解压缩包 tar xvzf xxx.tar.gz 切换到安装目录下 cd ...

  7. 开启mongod服务(Mongo运行错误:Failed to connect 127.0.0.1:27017,reason:errno:10061由于目标计算机积极拒绝,无法连接)

    问题:Mongo运行错误:Failed to connect 127.0.0.1:27017,reason:errno:10061由于目标计算机积极拒绝,无法连接 在Mongodb的安装过程中碰到的问 ...

  8. 每月IT摘录201805

    摘录自互联网的前辈心得: 一.技术:0.精通一个淘汰的技术对你没有任何价值.学习的精力有限,更应该花在值得学的技术上.比如网络.操作系统.数据结构.算法1.工作要有定力,更多的应该是关心问题如何更有效 ...

  9. 百度BAE的一些使用心得

    休眠会释放单元资源停止收费,那就不用被百度收费了

  10. 【校招面试 之 剑指offer】第16题 数值的整数次方

    方法1:直接求解,但是要注意特殊情况的处理:即当指数为负,且底数为0的情况. #include<iostream> using namespace std; template<typ ...