I'm trying to add new "commands" to an existing json file and I'm stuck, I have a .json file with subarrays.
This is how the file looks like:
{
"template_commands":{
"web":[
"Webadded cmds are working!",
"Rights['0']"
],
"streamer":[
"This is only for Streamers!",
"Rights['3']"
],
"admin":[
"This is only for Admins!",
"Rights['2']"
],
"mod":[
"This is only for mods",
"Rights['1']"
],
"taka":[
"taka",
"Rights['2']"
]
},
"doggo_counter":0,
"admins":{
"touru":"name",
"juufa":"name"
}
}
I want to add new values into "template_commands" Here is the php code:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
function get_data() {
$name = $_POST['name'];
$file_name='commands'. '.json';
if(file_exists("$file_name")) {
$current_data=file_get_contents("$file_name");
$array_data=json_decode($current_data, true);
$extra=array(
$_POST['name'] => array($_POST['branch'],$_POST['year'])
);
$array_data['template_commands'][]=$extra;
echo "file exist<br/>";
return json_encode($array_data);
}
else {
$datae=array();
$datae[]=array(
'Name' => $_POST['name'],
'Branch' => $_POST['branch'],
'Year' => $_POST['year'],
);
echo "file not exist<br/>";
return json_encode($datae);
}
}
$file_name='commands'. '.json';
if(file_put_contents("$file_name", get_data())) {
echo 'success';
}
else {
echo 'There is some error';
}
}
?>
It almost works but it puts the newly added in like this:
"0":{
"Test":[
"Lets see if this works!",
"1"
]
}
What am I doing wrong? I tried it with array_push() as well and it didn't work either.
The source of your problem is the way you're adding your element:
$array_data['template_commands'][]=$extra;
By using [] you're instructing PHP to add a new entry while automatically determining the key (which will be 0, since your array is associative, not numerical). So what you're doing can be shown as trying to add
[
'Test' => [
"Lets see if this works!",
"1"
]
]
at the next available numerical index, in this case zero.
This way of adding is suitable for numeric arrays, but not for associative ones. For them, you should explicitly define the index. So what you really want is to add
[
"Lets see if this works!",
"1"
]
under the key Test. To achieve that, change your code to this:
// only the inner array of what you used
$extra = array($_POST['branch'], $_POST['year']);
// the index is directly specified during assignment
$array_data['template_commands'][$_POST['name']] = $extra;
Related
I have some JSON that looks like this:
{
"order_id":"59.1595",
"quantity":"1",
"orderline":"61b9f15a158ee",
"customer_id":"59",
"product_thumbnail":"https:\/\/website.nl\/cms\/images\/producten\/deelpaneel\/afbeeldingen\/_deelpaneel_foto_op_rvs.jpg",
"rulers":"cm",
"product_data":{
"id":"custom",
"dpi":"50",
"name":"Deelpaneel",
"size":"1000x550",
"bleed":"10",
"sides":{
"id":1,
"name":"Frontside",
"name_nl":"Voorkant",
"template_overlay":"https:\/\/website.nl\/cms\/images\/producten\/deelpaneel\/templates\/2_deelpaneel_100x55cm1cmafstandhouders.svg"
}
},
"safety":"",
"has_contour":"false",
"preview_link":"",
"redirect_link":"https:\/\/website.nl\/winkelwagen",
"procheck":"n"
}
I create it with PHP and use json_encode.
My question is how do I get brackets around the inside of sides?
Like in this example:
"sides": [
{
"id": 1,
"name": "Frontside",
"name_nl": "Voorkant",
"template_overlay": null
},
{
"id": 2,
"name": "2 side en",
"name_nl": "2 side nl",
"template_overlay": null
},
{
"id": 3,
"name": "3 side en",
"name_nl": "3 side nl",
"template_overlay": null
}
],
"safety": 10,
This is how I create that part with PHP:
<?PHP
if(!empty($uploadarray['product_data']['sides'])){
// Multiple sides
}else{
$uploadarray['product_data']['sides']['id'] = 1;
$uploadarray['product_data']['sides']['name'] = 'Frontside';
$uploadarray['product_data']['sides']['name_nl'] = 'Voorkant';
$uploadarray['product_data']['sides']['template_overlay'] = $templateoverlay;
}
?>
Then I create the entire JSON with: $json = json_encode($uploadarray);
I've read that you need to wrap it in another array but I can't get it to work.
For example:
array(array($uploadarray['product_data']['sides']['id'] = 1));
Or
array($uploadarray['product_data']['sides']['name'] = 'Frontside');
Just output the same json result.
First create your array
$side = [
'id' => 1,
'name' => 'Frontside',
'name_nl' => 'Voorkant',
'template_overlay' => $templateoverlay
];
Then, add it :
// Check this -----------------------vv
$uploadarray['product_data']['sides'][] = $side;
Your $sides variable does not contain an array with multiple entities but just one "dictionary" (one JSON object). If you e.g. add a loop around, it should work:
<?php
// loop over whatever generates the sides
$sides_array = [];
$sides_array['id'] = 1;
$sides_array['name'] = 'Frontside';
$sides_array['name_nl'] = 'Voorkant';
$sides_array['template_overlay'] = $templateoverlay;
if(empty($uploadarray['product_data']['sides'])){
// initialize "sides"
$uploadarray['product_data']['sides'] = [];
}
$uploadarray['product_data']['sides'][] = $sides_array;
?>
i am a bit confused as i have tried what i understand about fetching an item in an array in an object .
let me break down
in my client endpoint
$client=Client::where('id',$client)->firstOrFail();
$arr = json_decode($client->attributes);
return response()->json($arr);
when i return like this
return response()->json($client->attributes);
i get
{
"full_details_acknowledgement": "10",
"offer_letter_acknowledgement": "10",
"offer_letter": "10",
"offer_letter_variables": [
"basic_salary",
"housing_allowance",
"transport_allowance",
"meal",
"entertainment",
"hazard_allowance",
"leave_allowance",
"utility",
"monthly_gross_salary",
"statutory_deductions",
"employee_pension",
"payee_tax",
"total_deductions",
"net_monthly_salary",
"austin"
],
"company": "global-manpower"
}
i am trying to get the values of offer_letter_variables and safe them in a variable
like this , this is also what i have tried
foreach ($client->attributes['offer_letters_variables'] as $variable){
$offer_letters_variables->put($variable,isset($request->{$variable}) ? $request->{$variable} : 0 );
}
but if i try it as the above i have the error
"message": "Cannot access offset of type string on string"
heres a full view of my code(i commented out some parts)
public function submitSingleUploadCandidates($client,Request $request){
$request->validate([
'job_role_id'=>'required',
'mail_template_id'=>'required',
'first_name'=>'required',
'last_name'=>'required',
'user_type'=>'required',
'email'=>'required',
]);
$job_level=JobLevel::find($request->job_level_id);
$job_role=JobRole::findOrFail($request->job_role_id);
$mail_template=MailTemplate::findOrFail($request->mail_template_id);
$client=Client::where('id',$client)->firstOrFail();
//return response()->json($client->attributes);
// $arr = json_decode($client->attributes);
//dd($client);
// return response()->json(gettype($arr));
// return response()->json($arr);
$offer_letters_variables=collect([]);
//return response()->json($offer_letters_variables);
// $var = $client->attributes[''];
// dd($var);
foreach ($client->attributes['offer_letters_variables'] as $variable){
$offer_letters_variables->put($variable,isset($request->{$variable}) ? $request->{$variable} : 0 );
}
$attr=collect(['offer_letter_variables'=>$offer_letters_variables]);
$user=User::where('email',$request->email)->first();
if ($user){
Session::flash('fail', 'Candidate with email already exist');
$payload=['status'=>'fail','details'=>'Candidate with email already exist'];
return response()->json($payload, 200);
return redirect()->back()->withInput();
}
$password=Str::random(7);
$job_level_id = $job_level->id ?? null;
$new_user=User::create([
'client_id'=>$client->id,
'email'=>$request->email,
'emp_num'=>$request->emp_num,
'first_name'=>$request->first_name,
'last_name'=>$request->last_name,
'stage_id'=>1,
'user_type'=>$request->user_type,
'job_level_id'=>$job_level_id,
'job_role_id'=>$job_role->id,
'attributes'=>$attr,
'password'=>Hash::make($password),
]);
// $mail_constants['MacTay Signature Banner'] = '';
$mail_constants = $this->getMailConstants($new_user);
$mail_constants['candidate_password']=$password;
$mail_constants['deadline']=Carbon::now()->addWeekdays(2)->format('D d M, Y');
$mail_constants['admin_name']=auth()->user()->name;
$mail_content=$this->convertMailTemplateToEmail($mail_template,$mail_constants);
$mail_template->subject = str_replace('{{job_role}}', $mail_constants['job_role'], $mail_template->subject);
$mail_template->subject = str_replace('{{client_name}}', $mail_constants['client_name'], $mail_template->subject);
Mail::to($new_user->email)->send(new AdminSendMail($mail_content,$mail_template->subject));
$message="Your account has been created on Mactay App. Email: {$new_user->email}, Temp Password: {$password}. URL: onboarding.mactay.com";
SendSMSJob::dispatch($new_user->phone,$message);
activity()->withProperties(['client_id' => $client->id])->log('Upload single candidate to '.$client->name);
Session::flash('success', 'Successfully Uploaded Single Candidates Details');
$payload=['status'=>'success','details'=>'Successfully Uploaded Single Candidates Details'];
return response()->json($payload, 200);
}
please what am i doing wrong, please help , thanks in advance
You forgot to json_decode $client->attributes
$clientAttributes = json_decode($client->attributes);
foreach ($clientAttributes->offer_letter_variables as $variable){
$offer_letters_variables->put(
$variable,
$request->{$variable} ?? 'not set'
);
}
$attr = collect(['offer_letter_variables' => $offer_letters_variables]);
if you want to access it like an array you can json_decode the value like as an associative array.
$clientAttributes = json_decode($client->attributes, true);
dd($clientAttributes['offer_letter_variables']);
Also not that you have misspelled offer_letter_variables as offer_letters_variables in you foreach loop.
You will get offer_letter_variables like this.
$offerLetters = 0;
$client=Client::where('id',$client)->firstOrFail();
if(isset($client->attributes['offer_letter_variables'])){
$offerLetters = $client->attributes['offer_letter_variables'];
}
do you need to use the second parameter of json_decode ? For remember, used if it's an associative array
$client=Client::where('id',$client)->firstOrFail();
$arr = json_decode($client->attributes);
What return gettype() ? Array ?
thanks to #maazin , the solution was to use json_decode $client->attributes and then use foreach like so
$clientAttributes = json_decode($client->attributes);
foreach ($clientAttributes->offer_letter_variables as $variable){
$offer_letters_variables->put(
$variable,
$request->{$variable} ?? 'not set'
);
}
$attr = collect(['offer_letter_variables' => $offer_letters_variables]);
I am trying to consume REST API service and check if the parameter coming exist in some tables.
Scenarios:
Check if the value exist in the license table,
If not, check the license used table
if not in either of the table then it does not exist; print out an error message
My problem:
If I use just if-else, it works but if I include the else if it returns null
What am I doing wrong?
Code:
<?php
header("Content-Type:application/json");
//if (isset($_GET['licence']) && $_GET['licence']!="") {
$licence = $_GET['licence'];
$query = mysqli_query($con,"SELECT id, licence,
period, users FROM licence WHERE licence='$licence'");
$counts = mysqli_num_rows($query);
if ($counts>0) {
// get retrieved row
while($row = mysqli_fetch_array($query)){
// create array
$user_arr=array(
"status" => true,
"message" => "Successfully Validated!",
"id" => $row['id'],
"licence" => $row['licence'],
"period" => $row['period'],
"user" => $row['users'],
"mstatus" => $row['status']
);
}
} elseif ($counts==0) {
$querys = mysqli_query($con,"SELECT
COUNT(licence) num,
licence, period, users FROM licence_used
WHERE licence='$licence'");
$row = mysqli_fetch_array($querys);
$count = mysqli_num_rows($querys);
if ($count > 0) {
if ($row['num'] == $row['users']) {
$user_arr=array(
"status" => false,
"message" => "Licence key entered has been used by ".$row['users']." users. Please purchase another licence.",
);
} else {
while($row = mysqli_fetch_array($querys)){
// create array
$user_arr=array(
"status" => true,
"message" => "Successfully Validated!",
"id" => $row['id'],
"licence" => $row['licence'],
"period" => $row['period'],
"user" => $row['users'],
"mstatus" => $row['status']
);
}
}
}
} else {
$user_arr=array(
"status" => false,
"message" => "Invalid Licence Key Entered. Please contact the software company.",
);
}
// make it json format
print_r(json_encode($user_arr));
//}
?>
It is good practice not avoid nesting so many ifs/elses, it makes the code harder to read and debug.
The last else is unreachable and there is no way the total results will be < 0
You could also split the cases in functions and call them accordingly, another good way to make the code readable.
I did some changes to your code as an example, code looks awful in here so I used pastebin instead.
https://pastebin.com/wuryVaph
(I had to include some code because stackoverflow demands that in order to use the pastebin, but ignore this if you want to, is a recommended function to print the results).
<?php
header("Content-Type:application/json");
function reply($reply){
print json_encode($reply);
exit;
}
I hope it helps.
I want to insert data in Mongo database using PHP script, in year wise documents so that it may look like this (All years in one document);
cars{
2017{
car=Motorolla
color = blue
}
2016{
car=Toyota
color = green
}
2015{
car=Corolla
color = black
}
}
I wanted to add the document but it prompts
Document can't have $ prefixed field names: $years[0]
Is it possible to make such schema in Mongo using PHP?
Code
<?php
try {
$car = 'Motorolla';
$color = 'blue';
//$car = 'Toyota';
//$color = 'green';
//$car = 'Corolla';
//$color = 'black';
$years = array(2017, 2016, 2015);
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$bulkWriteManager = new MongoDB\Driver\BulkWrite;
$document = ['_id' => new MongoDB\BSON\ObjectID, '$years[0]' => $car, '$years[1]' => $color]; // Making a query type
try {
$bulkWriteManager->insert($document); // Inserting Document
echo 1;
} catch(MongoCursorException $e) {
/* handle the exception */
echo 0;
}
$manager->executeBulkWrite('dbName.carsCol', $bulkWriteManager); // Going to DB and Collection
} catch (MongoDB\Driver\Exception\Exception $e) {
$filename = basename(__FILE__);
echo "The $filename script has experienced an error.\n";
echo "It failed with the following exception:\n";
echo "Exception:", $e->getMessage(), "\n";
}
?>
I do not want to add whole car object at once. I want to add Year object every time. Any help will be appreciable.
OR
Any relative answer so that I may get the data from Mongo Database according to the year?
Edit1
For first time creation. - Credits goes to #Veeram
<?php
try {
$car = 'Malibu';
$color = 'red';
$years = array(2017);
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$bulkWriteManager = new MongoDB\Driver\BulkWrite;
//{"car":"chevy", "color":"black", year: 2017}
$insert = ['car' => $car, 'color' => $color, 'year' => $years[0]];
try {
$bulkWriteManager -> insert($insert); // Inserting Document
echo 1;
} catch (MongoCursorException $e) {
echo 0;
}
$manager->executeBulkWrite('dbName.mycol', $bulkWriteManager); // Going to DB and Collection
} catch (MongoDB\Driver\Exception\Exception $e) {
$filename = basename(__FILE__);
echo "The $filename script has experienced an error.\n";
echo "It failed with the following exception:\n";
echo "Exception:", $e->getMessage(), "\n";
echo "In file:", $e->getFile(), "\n";
echo "On line:", $e->getLine(), "\n";
}
?>
For the updation- Credits goes to #Veeram
<?php
try {
$car = 'ChangedCar';
$color = 'changedColor';
$years = array(2017);
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$bulkWriteManager = new MongoDB\Driver\BulkWrite;
$query = ['cars.year' => $years[0]];
//{ $push: { "cars.$.data": { "car":"chevy", "color":"black"} }}
$update = ['$push'=> ['cars.$.data'=>['car' => $car, 'color' => $color]]];
try {
$bulkWriteManager->update($query, $update); // Inserting Document
} catch(MongoCursorException $e) {
}
$manager->executeBulkWrite('dbName.mycol', $bulkWriteManager); // Going to DB and Collection
} catch (MongoDB\Driver\Exception\Exception $e) {
$filename = basename(__FILE__);
echo "The $filename script has experienced an error.\n";
echo "It failed with the following exception:\n";
echo "Exception:", $e->getMessage(), "\n";
}
?>
The problem in this code is that it successfully insert the data for the first time but when i update the data it does not update it.
Example:
There is a document named as cars . Insert the data with object of year in one document. Let's say the Object is 2017, it contains color and car Model. As showing below; (Multiple objects with years. Year is unique in whole document.)
cars{
2017{
car=Motorolla
color = blue
}
2016{
car=Toyota
color = green
}
2015{
car=Corolla
color = black
}
}
If I want to update just make an object of 2017 like 2017{car=Updated-Motorolla color =Updated-blue} and insert in the document. It should update only the year 2017 object in side the document.
cars{
2017{
car=Updated-Motorolla
color =Updated-blue
}
2016{
car=Toyota
color = green
}
2015{
car=Corolla
color = black
}
}
You can try something like this. Its not possible to perform all the Mongo db operations just based off key as a value.
The first solution is written to stay close to OP's design.
Assuming you can add a key to the year.
{
"cars": [{
"year": "2017",
"data": [{
"car": "Motorolla",
"color": "blue"
}]
}, {
"year": "2016",
"data": [{
"car": "Toyota",
"color": "green"
}]
}]
}
Makes it easy to reference the year by its value.
For example to add a new value into the data array for year 2017. You can try the below code.
Uses update positional $ operator.
query part to reference the array where 2017 record is stored.
update part using push to add the new car record to the existing data array for 2017 row.
<?php
try {
$car = 'Malibu';
$color = 'blue';
$years = [2017];
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$bulkWriteManager = new MongoDB\Driver\BulkWrite;
//{"cars.year":2017}
$query = ['cars.year' => $years[0]];
//{ $push: { "cars.$.data": { "car":"chevy", "color":"black"} }}
$update = ['$push'=> ['cars.$.data'=>['car' => $car, 'color' => $color]]];
try {
$bulkWriteManager->update($query, $update); // Update Document
echo 1;
} catch(MongoCursorException $e) {
/* handle the exception */
echo 0;
}
$manager->executeBulkWrite('dbName.carsCol', $bulkWriteManager); // Going to DB and Collection
} catch (MongoDB\Driver\Exception\Exception $e) {
$filename = basename(__FILE__);
echo "The $filename script has experienced an error.\n";
echo "It failed with the following exception:\n";
echo "Exception:", $e->getMessage(), "\n";
}
?>
For accessing data by year you can run below query.
Use query positional $operator to find the array index using the query part and reference that value in projection part.
db.collection.find({"cars.year":2017}, {"cars.$.data":1});
Alternative Solution :
This will take care of everything as just inserts
You are better off saving each car entry in its own document.
{ "year" : 2017, "car" : "Motorolla", "color" : "blue" }
{ "year" : 2016, "car" : "Toyota", "color" : "green" }
{ "year" : 2015, "car" : "Corolla", "color" : "black" }
For each entry you can use:
db.collection.insert({"year":2017, "car":"Motorolla", "color":"blue"});
PHP Code:
//{"car":"chevy", "color":"black", year: 2017}
$insert = ['car' => $car, 'color' => $color, 'year' => $years[0]];
try {
$bulkWriteManager - > insert($insert); // Inserting Document
echo 1;
} catch (MongoCursorException $e) {
/* handle the exception */
echo 0;
}
For access data by year you can use
db.collection.find({"year":2017});
Updated PHP code:
<?php
try {
$cars = ['Motorolla','Toyota', 'Corolla'] ;
$colors = ['blue', 'green', 'black'];
$years = [2017, 2016, 2015];
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$bulkWriteManager = new MongoDB\Driver\BulkWrite;
$query1 =["year" => $years[0]];
$query2 =["year" => $years[1]];
$query3 =["year" => $years[2]];
$update1 = ['$set' => ['car' => $cars[0], 'color' => $colors[0]]];
$update2 = ['$set' => ['car' => $cars[1], 'color' => $colors[1]]];
$update3 = ['$set' => ['car' => $cars[2], 'color' => $colors[2]]];
try {
$bulkWriteManager->update($query1, $update1, ["upsert" => true]);
$bulkWriteManager->update($query2, $update2, ["upsert" => true]);
$bulkWriteManager->update($query3, $update3, ["upsert" => true]);
echo 1;
} catch(MongoCursorException $e) {
/* handle the exception */
echo 0;
}
$manager->executeBulkWrite('dbName.carsCol', $bulkWriteManager); // Going to DB and Collection
} catch (MongoDB\Driver\Exception\Exception $e) {
$filename = basename(__FILE__);
echo "The $filename script has experienced an error.\n";
echo "It failed with the following exception:\n";
echo "Exception:", $e->getMessage(), "\n";
}
?>
You can perform complex queries using aggregation pipeline and you can add index to make your response quicker.
Observations:
First Solution : Harder to update/insert data, but keeps everything together so easier to read data.
Second Solution :
Cleaner and simpler to do CRUD operations on documents and use aggregation pipeline to preform complex queries.
Try to change
$document = ['_id' => new MongoDB\BSON\ObjectID, '$years[0]' => $car, '$years[1]' => $color];
to something like:
$document = ['_id' => new \MongoDB\BSON\ObjectID, $years[0] => ['car' => $car, 'color' => $color]];
it gives such result in mongo:
{ "_id" : ObjectId("58a936ecfc11985f525a4582"), "2017" : { "car" : "Motorolla", "color" : "blue" }
If data about all cars must be in one document, you need to combine data fitst:
$cars = [
'2017' => [
'car' => 'Motorolla',
'color' => 'blue'
],
'2016' => [
'car' => 'Toyota',
'color' => 'green'
],
'2015' => [
'car' => 'Corolla',
'color' => 'black'
]
];
and than
$document = ['_id' => new \MongoDB\BSON\ObjectID, 'cars' => $cars];
It gives mongo document like:
{ "_id" : ObjectId("58aabc0cfc11980f57611832"), "cars" : { "2017" : { "car" : "Motorolla", "color" : "blue" }, "2016" : { "car" : "Toyota", "color" : "green" }, "2015" : { "car" : "Corolla", "color" : "black" } } }
I'm trying to search my collection for all occurrences where the body property contains all of the search keywords.
Example string - "The black cat is definitely purple."
Keywords "black", "purple" would return the string.
Keywords "black", "dog" would not return that string.
I've been cruising some topics and Googling, but cannot seem to find the proper syntax to do this.
Currently, I am taking an string of keywords separated by commas, exploding it into an array, and then putting that into a MongoRegex Object. I know my syntax is off, because when I send just one keyword it works, but when there is more than one, I do not get any results that I would expect to get.
Current Approach:
<?php
function search_topics($array)
{
include_once('config.php');
$collection = get_connection($array['flag']);
$x = 0;
$string = null;
$search_results = null;
$keywords = explode(',', $array['search']);
$end_of_list = count($keywords);
while ($x < $end_of_list)
{
$string = $string."/".$keywords[$x];
$x++;
if($x >= $end_of_list)
{
$string = $string."/i";
}
}
if ($string != null)
{
try
{
$regex_obj = new MongoRegex($string);
$cursor = $collection->find(array('body' => $regex_obj));
}
catch (MongoCursorException $e)
{
return array('error' => true, 'msg' => $e->getCode());
}
foreach($cursor as $post)
{
$search_results[] = $post;
}
if ($search_results != null && count($search_results) > 1)
{
usort($search_results, 'sort_trending');
}
return array('error' => false, 'results' => $search_results);
}
else
{
return array('error' => false, 'results' => null);
}
}
?>
So, if I send the string black in $array['search'], my object is formed with /black/i and would return that string.
If I send the string black,cat in $array['search'], my object is formed with /black/cat/i and returns null.
Can anyone point me in the right direction with this regex syntax stuff?
Thanks in advance for any help!
Nathan
Instead of regular expressions, I would suggest you look at MongoDB's text search functionality instead, which is specifically made for situations like this: http://docs.mongodb.org/manual/core/text-search/
You would use that like this (on the MongoDB shell):
use admin
db.runCommand( { setParameter: 1, 'textSearchEnabled' : 1 } );
use test
db.so.ensureIndex( { string: 'text' } );
db.so.insert( { string: "The black cat is definitely purple." } );
db.so.runCommand( 'text', { search: '"cat" AND "dog"' } )
db.so.runCommand( 'text', { search: '"cat" AND "purple"' } )
A command doesn't return a cursor, but instead it will return one document containing all the query results in the results field. For the last search command, the result is:
{
"queryDebugString" : "cat|purpl||||cat|purple||",
"language" : "english",
"results" : [
{
"score" : 2.25,
"obj" : {
"_id" : ObjectId("51f8db63c0913ecf728ff4d2"),
"string" : "The black cat is definitely purple."
}
}
],
"stats" : {
"nscanned" : 2,
"nscannedObjects" : 0,
"n" : 1,
"nfound" : 1,
"timeMicros" : 135
},
"ok" : 1
}
In PHP, for the runCommand to turn on text search, you'd use:
$client->database->command( array(
'setParameter' => 1,
'textSearchEnabled' => 1
) );
And the text search itself as:
$client->database->command( array(
'text' => 'collectionName',
'search' => '"cat" AND "purple"'
) );