Mongodb php get id of new document? - php

Creating a document:
$db->collection->insert($content);
// $newDocID = ???
I'm trying to get the new document's id. How? Thanks.

According to the docs the array you pass to insert will be amended with an _id field:
$db->collection->insert($content);
$newDocID = $content['_id'];

You can also get _id before insert. Just add _id field to document with new MongoId ie.
$content['_id'] = new MongoId();
$db->collection->insert($content);
Also there are nice benefits of this:
You don't need fsync flag like posted in comment by ZagNut in
previous answer. So you don't need to wait for reply from DB.
You don't need to actually insert anything to DB to get id. So you can
prepare some related objects and then insert or not insert them -
somewhat like transactions which mongo does not support (yet?).
You actually can generate id in your application, not in db, So you can
do whatever you want before or after insert.

This works for me:
$insertResult = $collection->insertOne($object);
$id = $insertResult->getInsertedId();

$newDocument = $db->collection->findAndModify ( $row, $row, null, array('new'=>true,'upsert' => true));
$strId = $newDocument['_id']->{'$id'};
http://php.net/manual/en/mongocollection.findandmodify.php

Related

modify the property value of JSON string stored in the Table Column

I have JSON string stored in my database column. I have to update that value in JSON string.
Here Is my table.
I want to update the state value inside it.
Example:
Name1 has State value KA so I want to update it to GJ.
What I have Tried So far?
UPDATE Customer
SET Detail = JSON_MODIFY(Detail , '$.Address.State', 'KA')
WHERE Name = 'name1';
Also Tried JSON_REPLACE is also not working.
But it shows the error:
FUNCTION Customer.JSON_MODIFY does not exist
Note: I know one workaround to do this but I didn't Want to fetch that string and update it completely. I want to update the particular detail in string.
I have also created the SQL Fiddle.
I am doing this on localhost. Below are the localhost detail.
Database server
Server: localhost (localhost via TCP/IP)
Software: MySQL
MySQL Version :5.5.24
phpMyAdmin
Version information: 3.5.1, latest stable version: 4.7.3
12.16 JSON Functions
...
Unless otherwise indicated, the JSON functions were added in MySQL
5.7.8.
...
Try:
UPDATE `Customer`
SET `Detail` = JSON_REPLACE(`Detail`, '$.Address.State', 'GJ')
WHERE `Name` = 'name1';
See db-fiddle.
As #wchiquito already pointed out, the JSON function were added in MySQL 5.7.8.
If you are not able to upgrade your MySQL installation you will have to take the workaround you mentioned. Using regular expression to replace your value is also not going to work without being able to define custom mysql functions. (Also there is a lot that can go wrong if you do operations like this with regex...)
So the only options I see you have, are:
upgrade your installation (award to #wchiquito).
Fetch the column, parse it and update it. Just as you mentioned yourself as a workaround.
That could look something like this:
// fetch the details
$sth = $pdo->prepare('select `Detail` from `Customer` where `Name` = ?');
$sth->execute(['name1']);
$detail = json_decode($sth->fetchColumn(), true);
// modify the state
$detail['Address']['State'] = 'KA';
// update the details
$sth = $pdo->prepare('update `Customer` set `Detail` = ? where `Name` = ?');
$sth->execute([json_encode($detail), 'name1']);
But I recommend just upgrading your MySQL installation if possible.
As you have an old MySQL, fetch the JSON string, decode it to an array, edit the array, re-encode it, and update your row:
// Fetch row
$json = $row['columnName'];
$array = json_decode($json, true); //true creates array and not stdClass
$array['valueToChange'] = 'some new value';
$json = json_encode($array);
// Perform update query
You can:
Use JSON_INSERT function to add the property to the object if it is not exist
Use JSON_REPLACE function substitutes the property only if it is exist
Use JSON_SET function to add the property if it is not found then replace it.
Hope this helps!

Filtering a query in parse that the key is a pointer

Im a bit new to the php side of parse, mainly objective-c and swift but I need to write some code that I can query a column (not the objectID one) to return the results..
The column I'm trying to query is a pointer to another class.
Here is the very basic code I have which returns all the rows in the class and the pointers data with the include key, but I need to filter or get only the row/s that I'm looking for.
$query = new ParseQuery("ClassB");
$query->includeKey("ClassA");
$results = $query->find();
In the php sdk I see an option to use equalTo which has a key and a value to it so I tried the following code.
so I choose the column that was the pointer , and its objectid to hopefully only return those row/s that has that object id.
$query = new ParseQuery("ClassB");
$query->includeKey("ClassA");
$query->equalTo("ColumnNameX", "yjdyaGRWP7");
$results = $query->find();
Nothing was returned and a php error was spit out
'pointer field ColumnNameX needs a pointer value' in /var/www/parse/src/Parse/ParseClient.php:326
So im not 100% sure why I cant filter by a ColumnNameX using its objectID which is a pointer to ClassA..
Did I miss something in the PHP docs..
I mean ideally in mysql to just get that row I want would be
SELECT * FROM ClassB WHERE ColunNameX = yjdyaGRWP7
That would return me the row of data, I can use a Join of course to get some info from ClassA as well.
Any thoughts on what im missing or do I need to first query the Class A to get a pointer, then in the equalTo do something like ("ColumnNamX" , $pointerfromClassA) ?
any one have anyone point out what im missing or have a code example.. I have seen some that use the objectID but I dont have access to that.
Ok I figured out one way to do this, not sure if this is the right way but it returns now what I want..
$query->equalTo("ColunNameX", array("__type" => "Pointer", "className" => "ColunNameX", "objectId" => "yjdyaGRWP7"));

how to update array in crate

I would like to know how I can update a value stored in an array, in crate.io
I have a blog table - blog_tbl
A column, with data type array - tags
A id column
Inside the tags column I have - ["tag1","tag2","tag3"]
I would to know how I would go about changing 'tag1' to 'tag99'
I tried
update blog_tbl set tags['tag1'] = 'tag99' where id = '1';
Also how would I add one the the end? so making it -
["tag1","tag2","tag3","tag4"]
many thanks
Unfortunately it's not possible currently. Array elements can only be selected using the subscript notation (e.g. select tags[1] from blog_tbl;) but not updated. Maybe add a GH issue requesting that feature.
You can use the pattern found here: https://crate.io/docs/reference/sql/occ.html#optimistic-update
However, that requires you to perform the modification on client side. Pseudo code:
updated = False
while not updated:
cursor.execute('SELECT array_field, "_version" FROM table WHERE id=1')
row = cursor.fetchone()
current_array_field = row[array_field]
current_array_field.append('newtag')
cursor.execute('UPDATE array_field = current_array_field WHERE id=1 AND "_version" = row[version]')
if cursor.rowcount > 0:
updated = True
This will make your update semi safe for concurrent updates of the same field.

Creating an array by looping through a mySQL database, capturing entries only once in PHP

i'm relatively new to coding and I need a little help. I'm basically trying to loop through an entry in a mySQL database and push any new entry into an array , so that it only comes up once in my array.
// SQL query
$response = $bdd->query('SELECT serie_bd FROM inventaire_bd');
//creating array to group all elements from the db so that they do not repeat
$serie_bd_groupe=array();
while($data_collected = $response->fetch())
{
if(array_key_exists($data_collected,$serie_bd_groupe)==false)
{
array_push($data_collected,$serie_bd_groupe);
}
}
Will this work? - it seems like the loop will just stay stuck after it comes accross an entry a second time because the if statement wont execute itself.
Also in the future, are their any php equivalent to jsfiddle.net so i can test code syntaxically?
Thank you for your time
Your array keys will be default integers, so you don't want to check those. Instead of this:
if(array_key_exists($data_collected,$serie_bd_groupe)==false)
you should do this:
if(!(in_array($data_collected,$serie_bd_groupe)))
http://php.net/manual/en/function.in-array.php
On the other hand, if you're expecting your collected data to be the array key rather than value, you'd do something like this, instead of your array_push:
$serie_bd_groupe[$data_collected] = 1;
then your key check would work.
If you are looking for UNIQUE values (serie_bd) from your database, update your query to include "DISTINCT" like this:
$bdd->query('SELECT DISTINCT serie_bd FROM inventaire_bd');
On the other hand, I think you are looking for http://phpfiddle.org/

mongo php insert with _id

I'm having trouble assigning my own _id value when inserting a new document into my Mongo collection. Here's my PHP:
$user = array(
'_id'=> new MongoId("4f626fdf1771a8e71a000000"),
'name'=> 'John Smith'
)
try {
if($col->insert($user)){
echo 'INSERTED';
}
} catch(MongoCursorException $e) {
echo "ERROR: ".$e;
}
This does not display an error, but it also doesn't insert the item to the collection. However I can assign a string variable instead of the MongoId type to the _id field, and it inserts.
By default, MongoDB driver runs commands in so called 'unsafe mode', when it does fire-and-forget for requests and does not check for error. So, if there's a duplicate key error, you won't know.
Try running the insert in safe mode like this:
$col->insert($user, array("safe" => true));
Oh, and you most certainly can make your own ObjectIds (contrary to what other answers here say).
Safe has been deprecated from future usage. To ensure you are using the right command use the write concern 'w'.
$col->insert($user, array('w'=>true))
See here:
http://php.net/manual/en/mongocollection.insert.php
You cannot create MongoDB object IDs on your own. So, there are two ways to insert a document into a collection:
Let MongoDB create the ID (safe!)
Choose the ID on your own, it could be anything except an array and it needs to be unique.
Reference: Object IDs
I never used the combination of PHP and MongoDB but try to simple assign a string to the _id field.

Categories