I have this collection :
...
"votes": [
{
"track1": [
{
"facebook": NumberLong(1)
}
],
"track2": [
{
"google": NumberLong(1),
"twitter": NumberLong(1)
}
]
}
],
...
I want to get the sum of the votes of track1 or track2 so what i did is :
$match = array(
'app_id' => (int)$appId,
'campaign_id' => (int)$campaign_id
);
$group = array(
'_id' => 'votes.0.'.$_t.'.0.facebook', //$_t => track id
'total' => array(
'$sum' => '$votes.0.'.$_t.'.0.facebook'
)
);
$res = $collection->aggregate(array(
array(
'$match' => $match
),
array(
'$group' => $group
)
)
);
$res_facebook = (int) $res['result'][0]['total'];
Result : 0
Where is the problem ?
Not sure if it will work, I didn't check it, but I had something similar.
This is how I would solve it:
$votes_array = json_decode($votes_array_json,TRUE);
$total_votes = 0;
foreach($votes_array as $track) {
foreach($track as $social_network => $votes) {
$total_votes = $total_votes + $votes;
};
};
Related
I had this looping function and what it does to fetch data then display the result in json format. In $subArray[] i try to call the looping function again so it can read if got any sub-nodes underneath. But seem the result not display as I expected to be.
function recursiveNode($ledgerID,$accountID){
global $ehorsObj;
$subArray = array();
$query_get_subchild = " SELECT accountLedgerID, accountID, accountMainID, accountName, active
FROM tblAccAccounts
WHERE accountMain = 'y'
AND accountSub = 'y'
AND accountMainID = '".$accountID."'
AND accountLedgerID = '".$ledgerID."'
ORDER BY accountName
";
$GetResult = $ehorsObj->FetchData($query_get_subchild, $ehorsObj->DEFAULT_PDO_CONNECTIONS);
while ($row3 = $GetResult->fetch()) {
$subArray[] = array('accountLedgerID' => $row3['accountLedgerID'], 'accountID' => $row3['accountID'], 'accountMainID' => $row3['accountMainID'], 'accountName' => $row3['accountName'], 'active' => $row3['active'], 'items' => recursiveNode($ledgerID, $row3['accountID']));
}
header("Content-type: application/json");
$result = json_encode($subArray);
echo $result;
}
it show the result (as image below)
and the result I expected to be like this
[
{
accountLedgerID: "LA1",
accountID: "LA95",
accountMainID: "LA5",
accountName: "SubGroup RunDeposit 1",
active: "y"
},
{
accountLedgerID: "LA1",
accountID: "LA2",
accountMainID: "LA5",
accountName: "SubGroup RunDeposit 2",
active: "y",
item: [
{
accountLedgerID: "LA1",
accountID: "LA125",
accountMainID: "LA2",
accountName: "Sub x2 Group RunDeposit 2",
active: "y",
items: [
{
accountLedgerID: "LA1",
accountID: "LA6",
accountMainID: "LA125",
accountName: "Sub x3 Group RunDeposit 2",
active: "y",
items: [ ]
}
]
}
]
}
]
function fetch_account ($dbresult, $ledgerID, $accountID) {
$result = array_filter($dbresult, function ($something) use ($ledgerID, $accountID) {
if ( $something['accountMainID'] == $accountID && $something['accountLedgerID'] == $ledgerID ) {
return true;
}
return false;
});
return array_values($result);
}
function recursiveNode($ledgerID,$accountID){
$testArray = [
[
'accountLedgerID' => 'LA1',
'accountID' => 'LA95',
'accountMainID' => 'LA5',
'accountName' => 'SubGroup RunDeposit 1',
'active' => 'y'
],
[
'accountLedgerID' => 'LA1',
'accountID' => 'LA2',
'accountMainID' => 'LA5',
'accountName' => 'SubGroup RunDeposit 2',
'active' => 'y'
],
[
'accountLedgerID' => 'LA1',
'accountID' => 'LA125',
'accountMainID' => 'LA2',
'accountName' => 'Sub x2 Group RunDeposit 2',
'active' => 'y'
],
[
'accountLedgerID' => 'LA1',
'accountID' => 'LA6',
'accountMainID' => 'LA125',
'accountName' => 'Sub x3 Group RunDeposit 2',
'active' => 'y'
]
];
$someArray = fetch_account($testArray, $ledgerID, $accountID);
$subArray = array();
$i = 0;
while (!empty($someArray[$i]) && $row3 = $someArray[$i]) {
$subArray[] = array(
'accountLedgerID' => $row3['accountLedgerID'],
'accountID' => $row3['accountID'],
'accountMainID' => $row3['accountMainID'],
'accountName' => $row3['accountName'],
'active' => $row3['active'],
'items' => recursiveNode($ledgerID, $row3['accountID'])
);
$i++;
}
return $subArray;
}
$myArray = recursiveNode('LA1', 'LA5');
$result = json_encode($myArray);
echo $result;
Breaking down the problem first, I think the recursive function isn't returning anything. I think this is indicative when your result has 'items' as null.
I am working on stock management system , with a large number of products and the customer wan to display the products in a Select2 widget exactly like kartik widget, and he want to represent the data more and more when scrolling down ,is it available or can be done using this widget or I have to create my own ?
this is my code
<?php
$url = Url::to ( [ 'products-list' ] );
echo Select2::widget ( [
'name' => 'state_10' ,
'options' => [
'id' => 'select_product' ,
'placeholder' => 'Select Product...' ,
'multiple' => false ,
'class' => ''
] ,
'pluginOptions' => [
'allowClear' => true ,
'minimumInputLength' => 1 ,
'ajax' => [
'url' => $url ,
'dataType' => 'json' ,
'data' => new JsExpression ( 'function(params) { return {q:params.term}; }' )
] ,
'escapeMarkup' => new JsExpression ( 'function (markup) { return markup; }' ) ,
'templateResult' => new JsExpression ( 'function(product) { console.log(product);return product.text; }' ) ,
'templateSelection' => new JsExpression ( 'function (subject) { return subject.text; }' ) ,
] ,
] );
?>
and I have this action in my controller and every thing is working well but I need to start with displaying a number of products in select2 and then when scrolling start getting more and more
controller action :
public function actionProductsList($q = null, $id = null) {
Yii::$app->response->format = Response::FORMAT_JSON;
$out = ['results' => ['id' => '', 'text' => '', 'qtyLeft' => '', 'serialNumbers' => '']];
if (!is_null($q)) {
$query = new Query;
$query->select(['product_id as id', new Expression("CONCAT(product_name,' -- ',product_qty_left) AS text, product_qty_left as qtyLeft, s.serial_number as serialNumbers")])
->from('product')
->join('LEFT JOIN', 'serial_number s', 's.r_product_id = product.product_id')
->where(['like', 'product_name', $q]);
// ->limit(20);
$command = $query->createCommand();
$data = $command->queryAll();
$out['results'] = array_values($data);
} elseif ($id > 0) {
$out['results'] = ['id' => $id, 'text' => AppProduct::find()->where(['product_id' => $id])->one()->product_name];
}
return $out;
}
According to the docs to use pagination, you must tell Select2 to add any necessary pagination parameters to the request by overriding the ajax.data setting. The current page to be retrieved is stored in the params.page property.
So you need to change the Select2 to the following
$url = Url::to ( [ 'products-list' ] );
echo Select2::widget ( [
'name' => 'state_10' ,
'options' => [
'id' => 'select_product' ,
'placeholder' => 'Select Product...' ,
'multiple' => false ,
'class' => ''
] ,
'pluginOptions' => [
'allowClear' => true ,
'minimumInputLength' => 1 ,
'ajax' => [
'url' => $url ,
'dataType' => 'json' ,
'data' => new JsExpression ( 'function(params) { return {q:params.term, page:params.page || 1}; }' )
] ,
'escapeMarkup' => new JsExpression ( 'function (markup) { return markup; }' ) ,
'templateResult' => new JsExpression ( 'function(product) { console.log(product);return product.text; }' ) ,
'templateSelection' => new JsExpression ( 'function (subject) { return subject.text; }' ) ,
] ,
] );
Select2 will expect a pagination.more value in the response. The value of more should be true or false, which tells Select2 whether or not there are more pages of results available for retrieval:
{
"results": [
{
"id": 1,
"text": "Option 1"
},
{
"id": 2,
"text": "Option 2"
}
],
"pagination": {
"more": true
}
}
so modify your server-side code to include the $page param and include the limit and offset in your query. i am using 5 records as limit currrently you can change it.
public function actionProductsList($page, $q = null , $id = null ) {
$limit=5;
$offset=($page-1)*$limit;
Yii::$app->response->format = Response::FORMAT_JSON;
$out = [ 'results' => [ 'id' => '' , 'text' => '' , 'qtyLeft' => '' , 'serialNumbers' => '' ] ];
if ( !is_null ( $q ) ) {
$query = new \yii\db\Query;
$query->select ( [ 'product_id as id' , new Expression ( "CONCAT(product_name,' -- ',product_qty_left) AS text, product_qty_left as qtyLeft, s.serial_number as serialNumbers" ) ] )
->from ( 'product' )
->join ( 'LEFT JOIN' , 'serial_number s' , 's.r_product_id = product.product_id' )
->where ( [ 'like' , 'product_name' , $q ] )
->offset ( $offset )
->limit ( $limit );
$command = $query->createCommand ();
$data = $command->queryAll ();
$out['results'] = array_values ( $data );
$out['pagination'] = [ 'more' => !empty($data)?true:false ];
} elseif ( $id > 0 ) {
$out['results'] = [ 'id' => $id , 'text' => AppProduct::find ()->where ( [ 'product_id' => $id ] )->one ()->product_name ];
}
return $out;
}
Update
There were a few fixes that I found in the above code and changed
Fix the offset $offset=($page-1)*$limit; rather than using the $page like ->offset($page) use the $offset like ->offset($offset).
Configure more results correctly to return false if no more results otherwise it keeps sending ajax calls to the server even if there are no more results so change it to $out['pagination'] = [ 'more' => !empty($data)?true:false ];
I wrote a mongodb query that I am having a hard time converting to php code:
var geoips = db.geoip.find().map(function(like){ return like.ip; });
var result = db.audit.aggregate([
{ $match: { ip: { $nin: geoips } } },
{ $group: {
_id: "$ip",
count: { $sum: 1 }
}}
]);
UPDATE:
The above query is the equivalent of the following Relation Database Query
Select ip,count(*)
from audit
where ip not in (select ip from geoip)
group by ip
Since I had to make this query in mongodb version 3.0, I was unable to take advantage of $lookup as suggested in an answer.
The below PHP code accomplishes the above objective and works as expected. It gets the distinct ips from geoip collection. It passes that result and does an aggregate on the audit collection to get the desired result.
$geoipcolln = $this->dbConn->selectCollection('geoip');
$geoips = $geoipcolln->distinct('ip');
$match = array('ip' => array('$nin' => $geoips));
$result = $this->collection->aggregate(
array(
'$match' => $match
),
array('$group' => array(
'_id' => '$ip',
'count' => array('$sum' => 1.0),
))
);
This can be done in one aggregation query using the $lookup operator as follows:
var result = db.audit.aggregate([
{
"$lookup": {
"from": "geoip",
"localField": "ip",
"foreignField": "ip",
"as": "geoips"
}
},
{ "$match": { "geoips.0": { "$exists": false } } },
{ "$group": {
"_id": "$ip",
"count": { "$sum": 1 }
}}
])
which can then be translated to PHP as:
<?php
$m = new MongoClient("localhost");
$c = $m->selectDB("yourDB")->selectCollection("audit");
$ops = array(
array(
"$lookup" => array(
"from" => "geoip",
"localField" => "ip",
"foreignField" => "ip",
"as" => "geoips"
)
),
array( "$match" => array( "geoips.0" => array( "$exists" => false ) ) ),
array( "$group" => array(
"_id" => "$ip",
"count" => array( "$sum" => 1 )
))
);
$results = $c->aggregate($ops);
var_dump($results);
?>
I have the following collection structure
{
"_id": {
"d_timestamp": NumberLong(1429949699),
"d_isostamp": ISODate("2015-04-25T08:14:59.0Z")
},
"XBT-USD-cpx-okc": [
{
"buySpread": -1.80081
}
I run the following aggregation
$spreadName ='XBT-USD-stp-nex';
$pipe = array(
array(
'$match' => array(
'_id.d_isostamp' => array(
'$gt' => $start, '$lt' => $end
)
)
),
array(
'$project' => array(
'sellSpread' =>'$'.$spreadName.'.sellSpread',
)
),
array(
'$group' => array(
'_id' => array(
'isodate' => array(
'$minute' => '$_id.d_isostamp'
)
),
'rsell_spread' => array(
'$avg' => '$sellSpread'
),
)
),
);
$out = $collection->aggregate($pipe ,$options);
and I get as a result the value 0 for rsell_spread whereas if I run a $max for instance instead of an $avg in the $group , I get an accurate value for rsell_spread , w/ the following structure
{
"_id": {
"isodate": ISODate("2015-04-25T08:00:58.0Z")
},
"rsell_spread": [
-4.49996▼
]
}
So I have two questions :
1/ How come does the $avg function does not work?
2/ How can I can a result not in an array when I use $max for example (just a regular number)?
The $avg group accumulator operator does work, it's only that in your case it is being applied to an element in an array and thus gives the "incorrect" result.
When you use the $max group accumulator operator, it returns the the highest value that results from applying an expression to each document in a group of documents, thus in your example it returned the maximum array.
To demonstrate this, consider adding a few sample documents to a test collection in mongoshell:
db.test.insert([
{
"_id" : {
"d_timestamp" : NumberLong(1429949699),
"d_isostamp" : ISODate("2015-04-25T08:14:59.000Z")
},
"XBT-USD-stp-nex" : [
{
"sellSpread" : -1.80081
}
]
},
{
"_id" : {
"d_timestamp" : NumberLong(1429949710),
"d_isostamp" : ISODate("2015-04-25T08:15:10.000Z")
},
"XBT-USD-stp-nex" : [
{
"sellSpread" : -1.80079
}
]
},
{
"_id" : {
"d_timestamp" : NumberLong(1429949720),
"d_isostamp" : ISODate("2015-04-25T08:15:20.000Z")
},
"XBT-USD-stp-nex" : [
{
"sellSpread" : -1.80083
}
]
},
{
"_id" : {
"d_timestamp" : NumberLong(1429949730),
"d_isostamp" : ISODate("2015-04-25T08:15:30.000Z")
},
"XBT-USD-stp-nex" : [
{
"sellSpread" : -1.80087
}
]
}
])
Now, replicating the same operation above in mongoshell:
var spreadName = "XBT-USD-stp-nex",
start = new Date(2015, 3, 25),
end = new Date(2015, 3, 26);
db.test.aggregate([
{
"$match": {
"_id.d_isostamp": { "$gte": start, "$lte": end }
}
},
{
"$project": {
"sellSpread": "$"+spreadName+".sellSpread"
}
}/*,<--- deliberately omitted the $unwind stage from the pipeline to replicate the current pipeline
{
"$unwind": "$sellSpread"
}*/,
{
"$group": {
"_id": {
"isodate": { "$minute": "$_id.d_isostamp"}
},
"rsell_spread": {
"$avg": "$sellSpread"
}
}
}
])
Output:
/* 0 */
{
"result" : [
{
"_id" : {
"isodate" : 15
},
"rsell_spread" : 0
},
{
"_id" : {
"isodate" : 14
},
"rsell_spread" : 0
}
],
"ok" : 1
}
The solution is to include an $unwind operator pipeline stage after the $project step, this will deconstruct the XBT-USD-stp-nex array field from the input documents and outputs a document for each element. Each output document replaces the array with an element value. This will then make it possible for the $avg group accumulator operator to work.
Including this will give the aggregation result:
/* 0 */
{
"result" : [
{
"_id" : {
"isodate" : 15
},
"rsell_spread" : -1.80083
},
{
"_id" : {
"isodate" : 14
},
"rsell_spread" : -1.80081
}
],
"ok" : 1
}
So your final working aggregation in PHP should be:
$spreadName ='XBT-USD-stp-nex';
$pipe = array(
array(
'$match' => array(
'_id.d_isostamp' => array(
'$gt' => $start, '$lt' => $end
)
)
),
array(
'$project' => array(
'sellSpread' =>'$'.$spreadName.'.sellSpread',
)
),
array('$unwind' => '$sellSpread'),
array(
'$group' => array(
'_id' => array(
'isodate' => array(
'$minute' => '$_id.d_isostamp'
)
),
'rsell_spread' => array(
'$avg' => '$sellSpread'
),
)
),
);
$out = $collection->aggregate($pipe ,$options);
I have a working MongoDB aggregate query which I can run via the MongoDB shell. However, I am trying to convert it to work with the official PHP Mongo driver (http://php.net/manual/en/mongocollection.aggregate.php).
Here is the working raw MongoDB query:
db.executions.aggregate( [
{ $project : { day : { $dayOfYear : "$executed" } } },
{ $group : { _id : { day : "$day" }, n : { $sum : 1 } } } ,
{ $sort : { _id : -1 } } ,
{ $limit : 14 }
] )
Here is my attempt (not working) in PHP using the Mongo driver:
$result = $c->aggregate(array(
'$project' => array(
'day' => array('$dayOfYear' => '$executed')
),
'$group' => array(
'_id' => array('day' => '$day'),
'n' => array('$sum' => 1)
),
'$sort' => array(
'_id' => 1
),
'$limit' => 14
));
The error from the above PHP code is:
{"errmsg":"exception: wrong type for field (pipeline) 3 != 4","code":13111,"ok":0}
Any ideas? Thanks.
The parameter in your Javascript is an array of 4 objects with one element each, in your PHP it's an associative array (object) with 4 elements. This would represent your Javascript:
$result = $c->aggregate(array(
array(
'$project' => array(
'day' => array('$dayOfYear' => '$executed')
),
),
array(
'$group' => array(
'_id' => array('day' => '$day'),
'n' => array('$sum' => 1)
),
),
array(
'$sort' => array(
'_id' => 1
),
),
array(
'$limit' => 14
)
));
In addition, if you have at least PHP5.4, you can use simpler array syntax. Transformation to PHP is then trivial, you simply replace curly braces with square brackets and colons with arrows:
$result = $c->aggregate([
[ '$project' => [ 'day' => ['$dayOfYear' => '$executed'] ] ],
[ '$group' => ['_id' => ['day' => '$day'], 'n' => ['$sum' => 1] ] ],
[ '$sort' => ['_id' => 1] ],
[ '$limit' => 14 ]
]);
You can also use the JSON array directly:
$json = [
'{ $project : { day : { $dayOfYear : "$executed" } } },
{ $group : { _id : { day : "$day" }, n : { $sum : 1 } } } ,
{ $sort : { _id : -1 } } ,
{ $limit : 14 }'
];
$pipeline = [];
foreach ($json as $stage) {
array_push($pipeline, toPHP(fromJSON($stage)));
}
$result = $c->aggregate($pipeline);
You can also use combination like this:
use function MongoDB\BSON\toRelaxedExtendedJSON;
use function MongoDB\BSON\fromPHP;
use function MongoDB\BSON\toPHP;
use function MongoDB\BSON\fromJSON;
$operator = '$dayOfYear';
$json = [];
array_push($json, toRelaxedExtendedJSON(fromPHP(
array('$project ' => array('day' => array($operator => '$executed')))
)));
array_push($json,
'{ $group : { _id : { day : "$day" }, n : { $sum : 1 } } } ,
{ $sort : { _id : -1 } } ,
{ $limit : 14 }'
);
$pipeline = [];
foreach ($json as $stage) {
array_push($pipeline, toPHP(fromJSON($stage)));
}
$result = $c->aggregate($pipeline);
or
$operator = '$dayOfYear';
$json = [];
array_push($json,
'{ $group : { _id : { day : "$day" }, n : { $sum : 1 } } } ,
{ $sort : { _id : -1 } } ,
{ $limit : 14 }'
);
$pipeline = [];
array_push($pipeline, array('$project ' => array('day' => array($operator => '$executed'))));
foreach ($json as $stage) {
array_push($pipeline, toPHP(fromJSON($stage)));
}
$result = $c->aggregate($pipeline);
If your aggregation query is dynamic or based on user-input be aware of NoSQL-Injection!
https://www.acunetix.com/blog/web-security-zone/nosql-injections/