Hướng dẫn com mongodb client mongoclient
Bài viết được sự cho phép của smartjob.vn Show
MongoDB hỗ trợ rất nhiều Driver cho các ngôn ngữ lập trình khác nhau. Trong bài viết này, SmartJob trình bày về việc kết nối, truy vấn từ PHP. Máy tính sử dụng: Windows 10, 64 bit, sử dụng bộ tích hợp XAMPP. Việc làm php và việc làm mongoBD hấp dẫn Bước 1. Tải về tập tin mở rộng dll tại đường link: Bước 2. Giải nén. Copy file php_mongodb.dll vào thư mục ext, ví dụ trên máy của tác giả là: C:\xampp\php\ext Bước 3. Tìm file php.ini , ví dụ, trên máy tác giả là: C:\xampp\php\php.ini . Chèn vào cuối tập tin này: extension=php_mongodb.dll Bước 4. Giả sử có thư mục: C:\xampp\htdocs\vy\mongo–php Gõ lệnh: composer require "mongodb/mongodb=^1.0.0" để tải thư viện bằng Composer về. Composer tự động tải về và thư mục có thêm 1 thư mục và 2 tập tin mới: Tạo 3 tập tin info.php, add.php, find.php để kiểm tra các tính năng mà thư viện MongoDB PHP cung cấp: Tập tin info.phpTập tin add.phpTập tin find.phpBước 5. Khởi chạy máy chủ PHP dựng sẵn php -S localhost:1111 -t C:\xampp\htdocs\vy\mongo-php Bước 6. Truy cập http://localhost:1111/info.php xem kết quả để thấy rằng extension MongoDB đã được cài đặt thành công trong PHP. Bước 7. Thêm dữ liệu bằng cách truy cập đường dẫn Bước 8. Tìm kiếm dữ liệu, bằng cách truy cập đường dẫn Để thực hiện nhiều thao tác đa dạng khác (đọc, ghi, sửa, xóa), bạn hãy xem thêm tài liệu như bên dưới. TÀI LIỆU THAM KHẢO 1. http://php.net/manual/en/mongodb.installation.windows.php Tải mã nguồn từ server SmartJob: mongo-php Bài viết gốc được đăng tải tại smartjob.vn Có thể bạn quan tâm:
Xem thêm tuyển dụng nhân viên it hấp dẫn trên TopDev From driver version 1.2 we introduced a new connection Class that has the same name across all of our official drivers. This is to ensure that we present a recognizable front for all our API’s. This does not mean that your existing application will break, but rather that we encourage you to use the new connection api to simplify your application development. Furthermore, the new connection class MongoClient acknowledges all writes to MongoDB, in contrast to the existing connection class Db that has acknowledgements turned off. Let’s take a tour of the MongoClient functions. MongoClient = function(server, options); MongoClient.prototype.open MongoClient.prototype.close MongoClient.prototype.db MongoClient.connect Outlined above is the complete MongoClient interface. The methods open, close and db work very similar to the existing methods on the Db class. The main difference is that the constructor is missing the database name from Db. Let’s show a simple connection using open as a code example speaks a thousand words. var MongoClient = require('mongodb').MongoClient , Server = require('mongodb').Server; var mongoClient = new MongoClient(new Server('localhost', 27017)); mongoClient.open(function(err, mongoClient) { var db1 = mongoClient.db("mydb"); mongoClient.close(); }); Notice that you configure the MongoClient just as you would have done the Db object. The main difference is that you access the db instances using the db method on the MongoClient object instead of using the Db instance directly as you would previously. MongoClient supports the same options as the previous Db instance you would have created. So, with a minimal change in our app, we can apply the new MongoClient connection code. But there is more and one direction you might consider int the future. That is the mongodb connection string. The URL connection format¶mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]] The URL format is unified across official drivers from 10gen with some options not supported on some drivers due to natural reasons. The ones not supported by the Node.js driver are left out for simplicities sake. Basic parts of the url¶
Replica set configuration:¶
Connection Configuration:¶
Connection pool configuration:¶
Write concern configuration:¶More detailed information about write concerns can be found at http://www.mongodb.org/display/DOCS/getLastError+Command
Auth options¶
Read Preference¶
MongoClient.connect¶The url format can be used with MongoClient.connect. Where possible MongoClient will pick the best possible default values for options but they can be overridden. This includes setting auto_reconnect to true and native_parser to true if it’s available. Below are some example on how to connect to a single server a replicaset and a sharded system using MongoClient.connect The single server connection¶var MongoClient = require('mongodb').MongoClient; MongoClient.connect("mongodb://localhost:27017/integration_test", function(err, db) { test.equal(null, err); test.ok(db != null); db.collection("replicaset_mongo_client_collection").update({a:1}, {b:1}, {upsert:true}, function(err, result) { test.equal(null, err); test.equal(1, result); db.close(); test.done(); }); }); A replicaset connect using no acknowledgment by default and readPreference for secondary¶var MongoClient = require('mongodb').MongoClient; MongoClient.connect("mongodb://localhost:30000,localhost:30001/integration_test_?w=0&readPreference=secondary", function(err, db) { test.equal(null, err); test.ok(db != null); db.collection("replicaset_mongo_client_collection").update({a:1}, {b:1}, {upsert:true}, function(err, result) { test.equal(null, err); test.equal(1, result); db.close(); test.done(); }); }); A sharded connect using no acknowledgment by default and readPreference for secondary¶var MongoClient = require('mongodb').MongoClient; MongoClient.connect("mongodb://localhost:50000,localhost:50001/integration_test_?w=0&readPreference=secondary", function(err, db) { test.equal(null, err); test.ok(db != null); db.collection("replicaset_mongo_client_collection").update({a:1}, {b:1}, {upsert:true}, function(err, result) { test.equal(null, err); test.equal(1, result); db.close(); test.done(); }); }); Notice that when connecting to the sharded system it’s pretty much the same url as for connecting to the replicaset. This is because the driver itself figures out if it’s a replicaset or a set of Mongos proxies it’s connecting to. No special care is needed to specify if it’s one or the other. This is in contrast to having to use the ReplSet or Mongos instances when using the open command. MongoClient connection pooling¶A Connection Pool is a cache of database connections maintained by the driver so that connections can be re-used when new connections to the database are required. To reduce the number of connection pools created by your application, we recommend calling MongoClient.connect once and reusing the database variable returned by the callback: var express = require('express'); var mongodb = require('mongodb'); var app = express(); var MongoClient = require('mongodb').MongoClient; var db; // Initialize connection once MongoClient.connect("mongodb://localhost:27017/integration_test", function(err, database) { if(err) throw err; db = database; // Start the application after the database connection is ready app.listen(3000); console.log("Listening on port 3000"); }); // Reuse database object in request handlers app.get("/", function(req, res) { db.collection("replicaset_mongo_client_collection").find({}, function(err, docs) { docs.each(function(err, doc) { if(doc) { console.log(doc); } else { res.end(); } }); }); }); MongoClient.connect options¶The connect function also takes a hash of options divided into db/server/replset/mongos allowing you to tweak options not directly supported by the unified url string format. To use these options you do pass in a hash like this: var MongoClient = require('mongodb').MongoClient; MongoClient.connect("mongodb://localhost:27017/integration_test_?", { db: { native_parser: false }, server: { socketOptions: { connectTimeoutMS: 500 } }, replSet: {}, mongos: {} }, function(err, db) { test.equal(null, err); test.ok(db != null); db.collection("replicaset_mongo_client_collection").update({a:1}, {b:1}, {upsert:true}, function(err, result) { test.equal(null, err); test.equal(1, result); db.close(); test.done(); }); }); Below are all the options supported for db/server/replset/mongos. db: A hash of options at the db level overriding or adjusting functionality not supported by the url¶
server: A hash of options at the server level not supported by the url.¶
replSet: A hash of options at the replSet level not supported by the url.¶
mongos: A hash of options at the mongos level not supported by the url.¶
|