Views In Mongo
we combine the result of more than one collections by using following concepts in mongo
db.createView(<view>, <source>, <pipeline>, <options>)
view - The name of the view to create.
source - The name of the source collection or view from which to create the view. The name is not the full namespace of the collection or view; i.e. does not include the database name and implies the same database as the view to create.
pipeline - An array that consists of the aggregation pipeline stage. db.createView creates the view by applying the specified pipeline to the source collection or view.
Collection 2: transactions
user_id is a foreign key
- aggregation
- lookup
- pipeline
View Definition:
Views act as read-only collections, and are computed on demand during read operations. MongoDB executes read operations on views as part of the underlying aggregation pipeline.db.createView(<view>, <source>, <pipeline>, <options>)
view - The name of the view to create.
source - The name of the source collection or view from which to create the view. The name is not the full namespace of the collection or view; i.e. does not include the database name and implies the same database as the view to create.
pipeline - An array that consists of the aggregation pipeline stage. db.createView creates the view by applying the specified pipeline to the source collection or view.
Create View:
Collection 1: UsersCollection 2: transactions
user_id is a foreign key
db.createView(
'userTransactions',
'users',
[
{
$lookup:
{
from:"transactions",
localField:"user_id",
foreignField:"user_id",
as:"Transactions"
}
}
]
);
Display View:
<?php
include("config.php");
$my_collection = $db->users;
$users = $my_collection->find(array('age'=>'25'));
echo 'Search Documents Based on Age';
echo '<pre>';
foreach($users as $user)
{
print_r($user);
}
echo '</pre>';
No comments: