what is the equivalent query from mysql to mongosb - php

im new to mongodb after years with mysql and trying to figure this equivalent query in mongodb with php composer
select * from table where (x > 0 and x < 30) or x = 'half' and sid = 1
$query = [
'$and' => [
[
'sid'=> 1
], ['$and' => [[
'info.x' => [
'$lt' => '30'
]
], [
'info.x' => [
'$gt' => '0'
]
], [
'info.x' => [ /// i want to put this in $or
'half'
]
]]
]
]
];
i want to display all what is greater then 0 and less then 30 or equal to 'half' where sid is 1
thanks

It must be
db.collection.find({
"$or": [
{ "x": { "$gte": 0, "$lte": 30 }},
{ "x": "half" }
],
"sid": 1
})
Or
$query = [
'$or'=> [
[ 'x'=> [ '$gte'=> 0, '$lte'=> 30 ]],
[ 'x'=> 'half' ]
],
'sid'=> 1
]

Related

Issue with mysql loop

Intuit integration.
With create invoice. I am needing to get items from a loop when I create the invoice.
I also tried by creating the loop first and using $items in the invoice create but also get an error. "Format Error. Expect an element of an array or an object."
Not liking my loop. How can I accomplish this
?
$theResourceObj = Invoice::create([
"TotalAmt" => 200.00,
"Line" => [
$queryitems = 'SELECT * FROM mydatabse',
$query_items = mysqli_query($con,$queryitems),
while($row = mysqli_fetch_array($query_items)) {
[
"Description"=> "Loop Description",
"DetailType"=> "SalesItemLineDetail",
"SalesItemLineDetail"=> [
"TaxCodeRef"=> [
"value"=> "TAX"
],
"Qty"=> 1,
"UnitPrice"=> 200,
"ItemRef"=> [
"name"=> "Loop Name",
"value"=> "5"
]
],
"LineNum"=> 1,
"Amount"=> 200.00,
"Id"=> "1"
],
}
],
"CustomerRef"=> [
"value"=> 1
],
"BillEmail" => [
"Address" => "email#somewhere.com"
]
]);
You can't put loops inside array literals.
Construct the array incrementally outside the call to Invoice::create().
$invoice = [
"TotalAmt" => 200.00,
"CustomerRef"=> [
"value"=> 1
],
"BillEmail" => [
"Address" => "email#somewhere.com"
]
];
$lines = [];
$queryitems = 'SELECT * FROM mydatabse';
$query_items = mysqli_query($con,$queryitems);
while($row = mysqli_fetch_array($query_items)) {
$lines[] = [
"Description"=> "Loop Description",
"DetailType"=> "SalesItemLineDetail",
"SalesItemLineDetail"=> [
"TaxCodeRef"=> [
"value"=> "TAX"
],
"Qty"=> 1,
"UnitPrice"=> 200,
"ItemRef"=> [
"name"=> "Loop Name",
"value"=> "5"
]
],
"LineNum"=> 1,
"Amount"=> 200.00,
"Id"=> "1"
];
}
$invoice['Line'] = $lines;
$theResourceObj = Invoice::create($invoice);

How do I extract subdocument in laravel mongodb

Hello Good Developers,
I am using jenssegers/laravel-mongodb package to query my MongoDB from Laravel.
Here's Fiddle for my query: https://mongoplayground.net/p/qzbNN8Siy-3
I have following JSON
[{
"id": "GLOBAL_EDUCATION",
"general_name": "GLOBAL_EDUCATION",
"display_name": "GLOBAL_EDUCATION",
"profile_section_id": 0,
"translated": [
{
"con_lang": "US-EN",
"country_code": "US",
"language_code": "EN",
"text": "What is the highest level of education you have completed?",
"hint": null
},
{
"con_lang": "US-ES",
"country_code": "US",
"language_code": "ES",
"text": "\u00bfCu\u00e1l es su nivel de educaci\u00f3n?",
"hint": null
}...
{
....
}
]
I am trying to run following command
db.collection.find({ 'id': "GLOBAL_EDUCATION" },{_id:0, id:1, general_name:1, translated:{ $elemMatch: {con_lang: "US-EN"} }})
Expecting result like this
[
{
"general_name": "GLOBAL_EDUCATION",
"id": "GLOBAL_EDUCATION",
"translated": [
{
"con_lang": "US-EN",
"country_code": "US",
"hint": null,
"language_code": "EN",
"text": "What is the highest level of education you have completed?"
}
]
}
]
Everything is fine while query directly in MoDB but issue arise when I am trying this in Laravel.
I've tried every possible known function from MongoDB package. but Not able to do this.
here's my Array
$findArray = [
[
'id' => "GLOBAL_EDUCATION",
],
[
'_id' => 0,
'id' => 1,
'general_name' => 1,
'translated' => [
'$elemMatch' => ['con_lang' => "US-EN"]
],
]
];
$model = GlobalQuestions::raw()->find($findArray) //OR
$data = GlobalQuestions::raw(function($collection) use ($findArray){
return $collection->find($findArray);
});
What I am doing wrong here, is this kind of Find() not possible here and I've to do this by aggregation?
Since no-one answered this, I am posting the solution if someone is having the same issue.
Doing some more R&D on the same I was able to do this using where and Project as well by Aggregation Pipelines.
----- Using Where() and Project() ------
$projectArray = [
'_id' => 0,
'id' => 1,
'general_name' => 1,
'translated' => [
'$elemMatch' => ['con_lang' => "FR-FR"]
],
];
$data = GlobalQuestions::where('id', '=', 'GLOBAL_EDUCATION')
->project($projectArray)
->get();
--- Using Aggregation and $unwind ---
$data = GlobalQuestions::raw(function($collection) {
return $collection->aggregate([
[
'$match' => [
'id' => "GLOBAL_EDUCATION"
]
],
[
'$unwind' => '$translated',
],
[
'$match' => [
'translated.con_lang' => "US-EN"
]
],
[
'$project' => [
'_id'=> 0,
'id'=> 1,
'general_name' => 1,
'translated' => 1,
]
]
]);
})->first();

PHP MongDb Find only one subarray

I need to recover one array from an array... I made in mongodb shell with this sentence:
db.users.aggregate([
{$match: {'userQueries.queryId': 'gr591dd6b06149d9.07403049'}},
{$project: {
userQueries: {$filter: {
input: '$userQueries',
as: 'query',
cond: {$eq: ['$$query.queryId', 'gr591dd6b06149d9.07403049']}
}},
_id: 0
}}
])
I'm using this driver: https://secure.php.net/manual/en/set.mongodb.php
My document looks like this:
{
"_id" : ObjectId("591dd67cc4ef6009ae38e292"),
"userId" : 0,
"email" : "dmance#dmance.org",
"password" : "dmance",
"fullName" : "daniel",
"organization" : "dmance",
"userQueries" : [
{
"queryResultArray" : [
{
"docsArray" : [
{
"hgnc_id" : "HGNC:26970"
}
],
"queryResultId" : 0,
"terms" : [
"COX2",
"COX20"
]
},
{
"docsArray" : [
{
"hgnc_id" : "HGNC:130"
}
],
"queryResultId" : 1,
"terms" : [
"ACT"
]
},
{
"docsArray" : [
{
"hgnc_id" : "HGNC:7422"
}
],
"queryResultId" : 2,
"terms" : [
"COX3"
]
}
],
"queryId" : "gr591dd6b06149d9.07403049",
"queryName" : "Unnamed query"
},
{
"queryResultArray" : [
{
"docsArray" : [
{
"hgnc_id" : "HGNC:26970"
}
],
"queryResultId" : 0,
"terms" : [
"COX2",
"COX20"
]
},
{
"docsArray" : [
{
"hgnc_id" : "HGNC:130"
}
],
"queryResultId" : 2,
"terms" : [
"COX3"
]
}
],
"queryId" : "gr591de08337e901.19728995",
"queryName" : "Unnamed query"
}
]
}
I want to get only the array matching the queryId field.
As I said I made it in the mongo shield but i cant translate it into php.
It was already answered. I'm sorry. This is how I solved the problem.
$mongo = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$pipeline = [
[
'$match' =>
[
'userQueries.queryId' => 'gr591dd6b06149d9.07403049',
],
],
[
'$project' =>
[
'userQueries' => [ [
'$filter' => [
'input' => '$userQueries',
'as' => 'query',
'cond' => [
'$eq' => [
'$$query.queryId', 'gr591dd6b06149d9.07403049',
]
],
],
],
],
'_id' => 0
],
],
];
$command = new \MongoDB\Driver\Command([
'aggregate' => 'users',
'pipeline' => $pipeline
]);
$cursor = $mongo->executeCommand('genenames', $command);

PHP format mysql result into json

I've been beating my head all day because of this.
How to convert the results from the image above into json format like this
{
"name": "João Batista Da Silva Júnior",
"y": "9.83",
"drilldown": "João Batista Da Silva Júnior",
"data": [
[
"assiduidade",
10
],
[
"normas",
9
],
[
"eficiencia",
10
],
[
"relacionamento",
10
],
[
"iniciativa",
10
],
[
"visao",
10
]
]
}
]
}
I'm trying this code but it doesn't reproduce the format required.
$info["aval"] = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
extract($row);
$info2 = ['name' => $auxiliar, 'y' => $media, 'drilldown' => $auxiliar, 'data' => [[$topico, floatval($nota)]]];
$info["aval"][] = $info2;
}

MapReduce using Command Failed to decode document from the server

I have a Test database with a collection called collection:
{
"_id": "576008e5b47a6120c800418d",
"UserID": "Paul",
"Page": "A"
}
I want to record webactivity and use mapreduce to get an outcome like
{
"_id": "Paul",
"value": {
"A": 1,
"B": 0,
"C": 0,
"D": 0,
"E": 0
}
}
For a start I tried a simple code with PHP 7 MongoDB Driver 1.1.7 MapReduce using command which failed to decode document from the server:
<?php
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$command = new MongoDB\Driver\Command(array(
"mapReduce" => "collection",
"map" => "function() { emit(this.UserID, 1); }",
"reduce" => "function(Users, Pages){".
"return Pages;}",
"out" => "ex"
));
try {
$cursor = $manager->executeCommand('Test.collection', $command);
$response = $cursor->toArray()[0];
} catch(MongoDB\Driver\Exception $e) {
echo $e->getMessage(), "\n";
exit;
}
var_dump($response);
?>
Any ideas will be appreciated thanks.
Not too sure if I would recommend MapReduce for this type of operation, would say the aggregation framework will do the aggregation with better performance since the operations are all done in native code without spawning the code to JavaScript for compiling (in the MapReduce case).
With the aggregation operation, all you would need is a $group pipeline that makes use of the $cond operator which allows you to tranform a logical condition into a value. In this case you'd want to specify the pages as keys and their count as the value, with the documents grouped by the UserID.
Consider running the following aggregation operation in mongo shell:
db.collection.aggregate([
{
"$group": {
"_id": "$UserID",
"A": {
"$sum": {
"$cond": [
{ "$eq": [ "$Page", "A" ] },
1,
0
]
}
},
"B": {
"$sum": {
"$cond": [
{ "$eq": [ "$Page", "B" ] },
1,
0
]
}
},
"C": {
"$sum": {
"$cond": [
{ "$eq": [ "$Page", "C" ] },
1,
0
]
}
},
"D": {
"$sum": {
"$cond": [
{ "$eq": [ "$Page", "D" ] },
1,
0
]
}
},
"E": {
"$sum": {
"$cond": [
{ "$eq": [ "$Page", "E" ] },
1,
0
]
}
}
}
}
])
which will produce the output:
{
"_id": "Paul",
"A": 1,
"B": 0,
"C": 0,
"D": 0,
"E": 0
}
for the above sample document.
For brevity, if suppose you have a list of the pages beforehand, you can dynamically produce the pipeline as follows:
var groupOperation = { "$group": { "_id": "$UserID" } },
pages = ["A", "B", "C", "D", "E"];
pages.forEach(function (page){
groupOperation["$group"][page] = {
"$sum": {
"$cond": [
{ "$eq": [ "$Page", page ] },
1,
0
]
}
};
})
db.collection.aggregate([groupOperation]);
Now, translating this to PHP follows:
<?php
$group_pipeline = [
'$group' => [
'_id' => '$UserID',
'A' => [
'$sum' => [
'$cond' => [ [ '$eq' => [ '$Page', 'A' ] ], 1, 0 ]
]
],
'B' => [
'$sum' => [
'$cond' => [ [ '$eq' => [ '$Page', 'B' ] ], 1, 0 ]
]
],
'C' => [
'$sum' => [
'$cond' => [ [ '$eq' => [ '$Page', 'C' ] ], 1, 0 ]
]
],
'D' => [
'$sum' => [
'$cond' => [ [ '$eq' => [ '$Page', 'D' ] ], 1, 0 ]
]
],
'E' => [
'$sum' => [
'$cond' => [ [ '$eq' => [ '$Page', 'E' ] ], 1, 0 ]
]
]
],
];
$aggregation = $collection->aggregate([ group_pipeline ]);
?>
Should you rather stick to MapReduce, then consider changing the map and reduce functions to :
db.collection.mapReduce(
function() {
var obj = {};
["A", "B", "C", "D", "E"].forEach(function (page){ obj[page] = 0; } );
obj[this.Page] = 1;
emit(this.UserID, obj);
},
function(key, values) {
var obj = {};
values.forEach(function(value) {
Object.keys(value).forEach(function(key) {
if (!obj.hasOwnProperty(key)){
obj[key] = 0;
}
obj[key]++;
});
});
return obj;
},
{ "out": { "inline": 1 } }
)
Which gives the output:
{
"results" : [
{
"_id" : "Paul",
"value" : {
"A" : 1,
"B" : 0,
"C" : 0,
"D" : 0,
"E" : 0
}
}
]
}
Translating the above mapReduce operation to PHP is trivial.

Categories