How to update the data in mongodb by id in my case? - php

I am sending an object to the php file, I need to save it in MongoDB with a special id which is sent by AJAX
here is the code:
$mongo = new MongoClient();
$editor = $db->editor;
$editor->update(
array( '_id' => $_GET['id'] ),
array( '$set' => json_decode($_POST['data']) )
);
but this code doesn't work
I have looked through a lot of questions familiar to my one here on stackoverflow
so, I really need help, because I can't get it!
thanks =)

Try this
Because the _id at mongo is not a simple string but a Object.
you can get this conclusion by try mongo under command line.
example: db.test.findOne({});
$editor->update(
array(
'_id' => new MongoId($_GET['id'])
),
array(
'$set' => json_decode($_POST['data']
)
);
More PHP MongoClass ID

Related

Get error 'MongoResultException' when use aggregate in mongoDB

When i use aggregatein PHP, i get error:
MongoResultException: localhost:27017: The 'cursor' option is
required, except for aggregate with the explain argument
I use mongoDB 3.6 and PHP 5.6
Please see the photo
My Code:
$dbconn = new MongoClient();
$c = $dbconn->selectDB("test")->selectCollection("users");
$ops = array(
array(
'$lookup' => array(
'from' => 'news',
'localField' => '_id',
'foreignField' => 'user_id',
'as' => 'user_docs'
)
)
);
$results = $c->aggregate($ops);
var_dump($results);
For other people who may run into the same problem, here is the solution.
The aggregator command was modified in version 3.6, as indicated in the documentation:
Changed in version 3.4: MongoDB 3.6 removes the use of aggregate command without the cursor option unless the command includes the explain option. Unless you include the explain option, you must specify the cursor option.
In Mongo, you could just add the cursor option without specifying any parameter, as specified in the documentation:
cursor: {}
In PHP, you would need to specify the option like this, new stdClass()corresponding to an empty object '{}' in Mongo :
$results = $c->aggregate($ops, ['cursor' => new \stdClass()]);
Here's how to do it for your example :
$dbconn = new MongoClient();
$c = $dbconn->selectDB("test")->selectCollection("users");
$ops = array(
array(
'$lookup' => array(
'from' => 'news',
'localField' => '_id',
'foreignField' => 'user_id',
'as' => 'user_docs'
)
)
);
$results = $c->aggregate($ops, ['cursor' => new \stdClass()]);
var_dump($results);
If you want to take advantage of calling 'cursor' to add parameters, such as batchSize, you can do it like this :
$results = $c->aggregate($ops, ['cursor' => ['batchSize' => 200]]);
All the parameters are listed in the documentation page linked above.

Best way to get data in laravel related to array of object ids with mongodb database

I have a table user data is as follow:
_id:ObjectId("mongodbid"),
name:"acdfgf",
skills:[ObjectId("skills id"),ObjectId("skill id 2")],
created_at:date,
updated_at:date
Now I have to get the user data with skills data based on there id in one hit.
Thanks in advance...
Try this, Consider User is your model name
[you should have set this model to access the mongoDb if you are using hybrid with mySql or MariaDB]
User::whereRaw(['skills' => '2'])->get();
let me know if this didn't work.
Please find answer
$m = new \MongoDB\Driver\Manager();
$command = new \MongoDB\Driver\Command([
'aggregate' => 'mytestusers',
'pipeline' => [
['$match' => ['name' => 'Pankaj Choudhary']],
['$unwind'=>'$skills'],
['$lookup' => array('from'=>'mytestskills','localField'=>'skills','foreignField'=>'_id','as'=>'sdfg')],
['$unwind'=>'$sdfg'],
['$group'=>array('_id'=>array('_id'=>'$_id','name'=>'$name','email'=>'$email'),'skills'=>array('$push'=>'$skills'),'sdfg'=>array('$push'=>'$sdfg'))],
],
'cursor' => new \stdClass,
]);
$cursor = $m->executeCommand('targetjob-plus', $command);
$result = $cursor->toArray();

how to update one record in Mogodb using PHP Codeigniter

I am finding a record by using this piece of code
1:) This statement find a record successfully.
$collection->findOne(array("email" => $email));
2:) Now i want to update a record where _id="5725301d76dc3a0809000029" i use this piece of code but its show me syntax error
$collection->update(array({ "_id" : ObjectId("5725301d76dc3a0809000029")}, {$set:{'title':'New MongoDB Tutorial'}}));
please Guide me how to update a record. If my syntax is Wrong so tel me the correct syntax. my query is ..
UPDATE userss SET title='My Title' WHERE _id=ObjectId("5725301d76dc3a0809000029");
Try this
$collection->update
(
array('_id' => new MongoId('5725301d76dc3a0809000029')),
array('$set' => array( 'title' => 'My Title' ))
);
The right syntax is given below...
It works fine :)
$collection = $this->mongo_db->db->selectCollection('surfinme');
$data = array('sitename'=> 'surfinme', 'title' => 'Mongodb');
$collection->update(array('_id' => new MongoId($uniqueId)), array('$set' => $data),array("upsert" => false));

Multiple elements of same name in PHP SOAP Call

I know this type of question has been asked a number of times. I have spent several hours reading and trying the offered solutions - but none appear to work for my situation.
I need to send a SOAP request to an API that can contain an element that repeats like so:
<operationNumbers>
<operationNumber>1234</operationNumber>
<operationNumber>1235</operationNumber>
<operationNumber>1236</operationNumber>
<operationNumber>1237</operationNumber>
</operationNumbers>
I did read that perhaps I could do this:
$buildRequest = Array(
'myheader' => Array(
'date' => MY_DATE,
'id' => Array(
'client' => CLIENT,
'clientRef' => MYREF
)
),
'operationNumbers' => Array (
Array('operationNumber' => '1234'),
Array('operationNumber' => '1235')
)
);
$request = $client->__soapCall( 'getMultiOpDets', array($buildRequest) );
Sadly this does not work and results in 'invalid request', if I send in a single operation number eg:
...
'operationNumbers' => Array (
'operationNumber' => '1234'
)
...
The request is successful. I've tried soapVars/soapParams but cannot get it working using this approach. Any hints/tips/help appreciated.
So, I solved it.
$operationNumbersArray = array('1234','1235');
...
'operationNumbers' => array(
'operationNumber' => $operationNumbersArray
)
During my testing and fiddling about, I had inadvertently removed another value that was mandatory. The API did not give warning of it's omission (sadly).
Here is the code I use:
$wsdl = 'https://your.api/path?wsdl';
$client = new SoapClient($wsdl);
$multipleSearchValues = [1, 2, 3, 4];
$queryData = ['yourFieldName' => $multipleSearchValues];
$results = $client->YourApiMethod($queryData);
print_r($results);

Using multiple modifier operations in a single update in PHP with MongoDB?

Is it possible to use multipule modifier operations within a single update in PHP with MongoDB?
For example, if I created the following document:
$doc = array(
'one' => 1,
'tags' => array(),
);
And then wanted to add another field ('new') and add an element to the 'tags' array, I could use the following two lines:
$collection->update(array('_id'=>$doc['_id']), array('$set' => array('new'=>'value')));
and
$collection->update(array("_id" => $doc['_id']), array('$addToSet' => array('tags'=>'my tag')));
Does anyone know it's possible to do both of these two operations in one 'update' command?
Thanks,
Neil
I haven't used mongo in a while, but I believe you should be able to:
$collection->update(array('_id'=>$doc['_id']), array(
'$set' => array('new'=>'value'),
'$addToSet' => array('tags'=>'my tag')
));

Categories