MongoDB是文档存储NoSQL数据库,而不是键值对和列存储NoSQL数据库,是目前最成熟可靠的NoSQL数据库。除了高效率、易扩展性和快速之外,MongoDB使用类似JavaScript的语言开发接口。
http://www.mongodb.org/
https://docs.mongodb.com/master/tutorial/install-mongodb-on-ubuntu/
mkdir -p /data/db //创建一个数据文件
sudo chown `id -u` /data/db/
$ mongod
http://localhost:27017/
http://localhost:28017/
> db.test.save( {a:1} )
WriteResult({ "nInserted" : 1 })
> db.test.find()
{ "_id" : ObjectId("5a57292be14e6a7aa446d496"), "a" : 1 }
> show dbs
> use db_name
> show collections: //输出选择出的数据库集合列表
> db.collection_name.find(query); //查找所有匹配条件的数据
> db.collection_name.findOne(query); //查找一条匹配条件的数据
> db.collection_name.insert(document) //插入一条数据
> db.collection_name.save(document); //保存一条数据到
> db.collection_name.update(query, {$set: data}); //用data对象的值更新匹配条件
> db.collection_name.remove(query); //删除所有匹配条件的数据
> printjson(document); //输出参数文档
$ npm install mongodb@1.3.23
以下步骤:
mongo-native-insert.js
const mongo = require('mongodb')
const dbHost = '192.168.200.158'
const dbPort = 27017
const {Db, Server} = mongo
const db = new Db('local',
new Server(dbHost, dbPort),
{safe: true}
)
db.open((error, dbConnection) => {
if (error) {
console.error(error)
return process.exit(1)
}
console.log('db state: ', db._state)
const item = {
name: 'Azat'
}
dbConnection.collection('messages').insert(item, (error, document) => {
if (error) {
console.error(error)
return process.exit(1)
}
console.info('created/inserted: ', document)
db.close()
process.exit(0)
})
})
mongo-native.js
const mongo = require('mongodb')
const dbHost = '192.168.200.158'
const dbPort = 27017
const {Db, Server} = mongo
const db = new Db('local', new Server(dbHost, dbPort), {safe: true})
db.open((error, dbConnection) => {
if (error) {
console.error(error)
process.exit(1)
}
console.log('db state: ', db._state)
dbConnection.collection('messages').findOne({}, (error, item) => {
if (error) {
console.error(error)
process.exit(1)
}
console.info('findOne: ', item)
item.text = 'hi'
var id = item._id.toString() // we can store ID in a string
console.info('before saving: ', item)
dbConnection
.collection('messages')
.save(item, (error, document) => {
if (error) {
console.error(error)
return process.exit(1)
}
console.info('save: ', document)
dbConnection.collection('messages')
.find({_id: new mongo.ObjectID(id)})
.toArray((error, documents) => {
if (error) {
console.error(error)
return process.exit(1)
}
console.info('find: ', documents)
db.close()
process.exit(0)
}
)
})
})
})
$ node mongo-native-insert
$ node mongo-native
Mongoskin比MongDB的原生驱动提供更好的API.
$ npm install mongoskin@0.6.1
P120
在MongoDB中添加seed数据
写Mocha测试
添加持久连接