var MongoClient = require('mongodb').MongoClient;
// Connect to the db
MongoClient.connect("mongodb://username:yourpassword@serveraddress:yourport/database", function(err, db) {
if(err) { return console.dir(err); }
var collection = db.collection('nodejs');
var doc1 = {'_id':'doc1', 'city':'taipei', 'num' :25};
var doc2 = {'_id':'doc2', 'city':'kaohsiung', 'num' :35};
//insert
collection.insert(doc1, {w:1}, function(err, result){});
collection.insert(doc2, {w:1}, function(err, result) {
console.log('insert');
collection.update({city:'taipei'}, {$set:{num:55}}, {w:1}, function(err, result) {});
collection.find().toArray(function(err, items) {});
collection.find({city:'taipei'}).toArray(function(err, docs){
console.log("retrieved records:");
console.log(docs);
});
});
var cursor = collection.find({city:'taipei'}).toArray(function(err, docs) {
console.log("Printing docs from Array");
docs.forEach(function(doc) {
console.log("Doc from Array ");
console.dir(doc);
console.log(doc.city);
});
});
//update
collection.update({city:'taipei'}, {$inc:{num:25}}, {w:1}, function(err, result) {
if(err)
{
console.log('fail update');
return console.dir(err);
}
console.log('Successfully update');
});
//remove
collection.remove({city:'kaohsiung'}, {w:1}, function(err, result) {});
});
2015-09-17
MongoDB using Node.js - Part 2
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment