laravel 连接mongodb

In this article we will see how to use MongoDB with Laravel (PHP framework). So first we need to install MongoDB and Laravel.

Laravel and MongoDB installation:

We will install Laravel and MongoDB one by one and I assume that you have PHP already installed with a web server.

Laravel Installation:

I assume LAMP environment is already configured. You can install Laravel simply through composer using following command if you have Composer already installed.

composer create-project laravel/laravel --prefer-dist

If you don’t know about composer or want to know more detailed installation and configuration of Larvel then Laravel documentation explained it in detail: http://laravel.com/docs/5.1#installation

MongoDB installation:

If you haven’t already installed MongoDB then MongoDB have separate guides for installing it own different Operating Systems. So check that: http://docs.mongodb.org/manual/installation/

Current version of MongoDB at this time is 3.x. But it you have MongoDB version 2.x installed and running on your machine then still feel free to use this tutorial, as it will work for 2.x as well and it have stuff related to 2.x difference in user creation section.

MongoDB driver for PHP:

PHP have official MongoDB driver that is called Mongo. It contains MongoClient class that is used by several packages which connect PHP with MongoDB.

You can install MongoDB driver on Windows OS using steps mentioned here: http://haafiz.me/development/installing-mongodb-driver-mongoclient-for-php-on-windows

To install MongoDB driver on ubuntu  or other Linux distributions, follow steps mentioned here: http://haafiz.me/development/installing-mongodb-driver-mongoclient-for-php-on-ubuntu

To check if MongoDB driver is successfully installed, try instantiating MongoClient class.

Laravel Package for MongoDB:

Laravel have several MongoDB related packages and some of them not work for Laravel 5.x (current versions at time of this writing). Based on several factors like number of contributers, number of commits, releases and documentation on github, simplicity and ease of use, I suggest using jenssegers/laravel-mongodb which is also knowns as Moloquent.

Installation:

To install for Laravel 5.1, install latest stable version using composer.

composer require jenssegers/mongodb

In config/app.php :

Add below line in providers array:

Jenssegers\Mongodb\MongodbServiceProvider::class,

And add in same file, add below line in aliases array:

‘Moloquent‘ => ‘Jenssegers\Mongodb\Model‘,

Moloquent Configurations:

In app/config/database.php, add MongoDB connection detail:

‘mongodb‘ => array(
  ‘driver‘ => ‘mongodb‘,
  ‘host‘ => env(‘DB_HOST‘, ‘localhost‘),
  ‘port‘ => env(‘DB_PORT‘, 27017),
  ‘database‘ => env(‘DB_DATABASE‘, ‘l5‘),
  ‘username‘ => env(‘DB_USERNAME‘, ‘l5‘),
  ‘password‘ => env(‘DB_PASSWORD‘, ‘123456‘),
  ‘options‘ => array(
    ‘db‘ => ‘admin‘ // sets the authentication database required by mongo 3
  )
),

and make this mongodb connection, default connection.

‘default‘ => env(‘DB_CONNECTION‘, ‘mongodb‘),

If you have installed MongoDB just now then you will not have Database, username and password to provide in connection info. For that purpose you need to first create database, username and password.

Setting up MongoDB Database and User:

To create a MongoDB database, you need to start, execute “mongo” from command line. To do so you need to add MongoDB bin directory to your system path. And then run:

mongod

This will run mongo server to listen calls.

In case you see error like: “ data/db not found ” , then that means that this path doesn’t exist on your system or don’t have appropriate permissions. So either create and assign appropriate permissions at that location or with appropriate permissions create DB data folder at some other custom location and give DB path like:

mongod --dbpath custom/directory/path

Once it is running, mongo server will be listening for client calls. So you need to run mongo shell client by simply opening another shell instance and run :

mongo

This will open mongoDB shell.

Creating Database in MongoDB:

Using mongo client shell, you need to create your database

> use dbname
> db.insert({"key":"value"})

By executing above statement, use statement switches DB to “dbname”, and assigns value “dbname” to variable “db”  so you can use your desired DB name. If “dbname” is name of existing database then it will switch to that database or else it will create that Database if atleast one record is added to that database.

Setting up First User and access:

If you are using Mongo 3.0 or above, first of all you need to switch to “admin” database and creating a user with administrative rights for all databases.

> use admin
> db.createUser(
  {
    user: "siteUserAdmin",
    pwd: "password",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
  }
)

You can replace “siteUserAdmin” and “password” from above code with your desired admin username and password. Role “userAdminAnyDatabase” is a special role for administrating all databases and this role is at “admin” database.

Once you have this Admin user on admin DB, you need to create user for your required DB, in our case “dbname”.

> use records
> db.createUser(
  {
    user: "recordsUserAdmin",
    pwd: "password",
    roles: [ { role: "userAdmin", db: "records" } ]
  }
)

Here you can replace “recordsUserAdmin”,”password” and “dbname” with desired username, password and your intended database name. And this will set your admin user for that database.

If you are using MongoDB version 2.x then user creation is different. In version 2.x db.createUser() function is not present. You need to use db.addUser() like:

> use products
> db.addUser( { user: "user1",
              pwd: "password",
              roles: [ "readWrite", "dbAdmin" ]
            } )

So now you have DBname, username and password to put in you Laravel app/config/database.php

Extending Models from Moloquent:

Only thing that is left is to extend your models from “Moloquent” instead of “Eloquent”.  So a typical model will look like this:

<?php
namespace App\Models;

use Moloquent;

/**
 * Category Model
 *
 * @author Hafiz Waheeduddin
 */
class Category extends Moloquent
{
 public function tasks()
 {
 return $this->hasMany(‘App\Models\Task‘, ‘category_id‘);
 }
}

So after that you can simply run most of queries of query builder through category model. And can utilized ORM in similar way as Moloquent supports many types of relationships, so you can utilize them too.

Moloquent Detail and Documentation:

Moloquent have very good examples at github to understand it and use it. So for Moloquent usage, reference and understanding, please check moloquent github page .

时间: 2024-10-19 08:09:10

laravel 连接mongodb的相关文章

远程连接mongodb时,27017端口连接不上的解决办法

一.背景描述: 我在linux  RED7上安装了mongodb,并没有修改mongodb的配置文件.然后通过另外一台电脑用pymongo连接mongodb时,报错:timeout. ping IP 是成功的. telnet IP 27017 的时候,提示:27017端口连接不上. 二.解决过程: 各种百度,远程连接mongodb失败,网上资料显示原因有两个: 1.mongodb的配置文件中的bind_ip 默认为127.0.0.1,默认只有本机可以连接.  此时,需要将bind_ip配置为0.

python连接mongodb并操作

安装python连接mongodb的库文件pymongo pip install pymongo python连接mongodb程序 import pymongo conn = pymongo.MongoClient("ip",端口) db = conn.admin #连接库 db.authenticate("账号","密码") #用户认证 db=conn.jwh db.test.insert({'id':1,'name':'kaka','sex

nodejs:注册登录session出错以及连接Mongodb数据库时Error connecting to database解决方案

(1)nodejs:注册登录session出错 解决办法: 在app.js 中将var MongoStore =  require(connect-mongo')改为var MongoStore =  require(connect-mongo')(express) 即可: (2)连接Mongodb数据库时Error connecting to database解决方案 这种情况下是自己的mongodb数据库没有装好 解决办法: a.在官网上下载安装数据库 b.在mongodb文件夹里面新建文件

使用mongo-java-driver-3.0.2连接MongoDB数据库

这里使用的mongodb的java驱动版本是:3.0.2,文件名mongo-java-driver-3.0.2.jar下载网址(也可以下载其它版本):http://central.maven.org/maven2/org/mongodb/mongo-java-driver/ 也可以查看相关的mongodb的api:http://api.mongodb.com/java/current/index.html package utils; import java.net.UnknownHostExc

java连接mongodb源码解读

用mongdb也大半年了,一直是业务上的逻辑实现了就ok.然而这样并不能进步--因此今天查了查java连接mongodb驱动的源码,搜到的各种信息整合一下,方便以后深入的使用. 先贴连接数据库代码  List<ServerAddress> replicaSet = new          ArrayList<ServerAddress>();          replicaSet.add(new ServerAddress("127.0.0.1", 2701

node连接mongoDB篇

一般介绍: 由于mongodb数据库在javascript脚本环境中支持bson对象(json对象的二进制形式)的存取,因此对于数据的存取的效率是非常高的.在mongodb数据库中,将每一条等待插入的数据记录存储在内存中,因此,该数据库是一种非阻塞型数据库,在需要记录大量日志数据,实时测量数据或实时统计数据时,该数据库可以达到令人满意的效果.用于mongodb数据库支持在查询语句内使用javascript函数,也大大加强了它读取数据的能力.另外,mongodb数据库是一个面向文档的数据库,它允许

[MongoDB学习笔记-02] Node.js连接MongoDB的两种方法

MongoDB Node.js驱动程序是被官方所支持的原生Node.js驱动程序,他是至今为止最好的实现, 并且得到了MongoDB官方的支持.MongoDB团队已经采用MongoDB Node.js驱动程序作为标准方法. npm install mongodb@1.4.3 // MongoDB Node.js驱动程序 npm install mongoose@3.8.8 //mongoose模块 要从Node.js连接MongoDB数据库我们有两种方法可选择: 通过实例化mongodb模块中提

java连接MongoDB数据库

这段时间尝试了一下MongoDB,感觉十分易用,方便,相比关系型的数据库来说优势也很大,于是尝试了下使用java连接MongoDB,并进行了 基本的增删改查操作. 首先先在控制台中连接数据库,查看数据库有几个表. 现在,新建一个maven工程,pom.xml中的依赖如下: <!-- WICKET DEPENDENCIES --> <dependency> <groupId>org.apache.wicket</groupId> <artifactId&

Java连接MongoDB

1.创建连接用户 > mongo ip:port > use test > db.addUser("root", "123456") > db.auth("root","123456") (登陆验证) 2.java连接mongodb的驱动,下载地址:https://github.com/mongodb/mongo-java-driver/downloads. 3.测试代码 import java.net