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 .

转载于:https://www.cnblogs.com/mengxiaotian/p/5294786.html

MongoDB 中,可以使用聚合管道来进行多表查询。聚合管道是一种操作数据的框架,可以在多个阶段对数据进行转换和处理。下面是一个使用 MongoDB 聚合管道进行多表查询的示例: 假设我们有两个集合,一个是用户集合(users),一个是订单集合(orders)。每个订单都对应一个用户。我们想要查询所有订单,并将其对应的用户信息也一并返回。 1. 首先,在 orders 集合中添加一个字段 userId,表示该订单对应的用户 ID。 2. 使用聚合管道进行查询,具体步骤如下: a. 使用 $lookup 阶段连接 users 集合和 orders 集合,将 orders 中的 userId 与 users 中的 _id 进行匹配。$lookup 阶段会将匹配的用户信息添加到每个订单文档中。 b. 使用 $unwind 阶段展开 orders 集合中的数组字段(如果有的话)。 c. 使用 $project 阶段选择要返回的字段,可以同时选择 orders 和 users 集合中的字段。 d. 使用 $match 阶段筛选符合条件的订单,可以根据订单状态、时间等条件进行筛选。 下面是一个示例代码: ``` db.orders.aggregate([ { $lookup: { from: "users", localField: "userId", foreignField: "_id", as: "user" } }, { $unwind: "$items" }, { $project: { _id: 1, userId: 1, status: 1, total: { $sum: "$items.price" }, user: { $arrayElemAt: [ "$user", 0 ] } } }, { $match: { status: "completed" } } ]) ``` 这个查询会返回所有状态为 completed 的订单,每个订单文档中都包含一个 user 子文档,其中包含该订单对应的用户信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值