I am trying to create new objects on MongoDB via PHP with personalized IDs, like this:
$user = Array(
'_id' => "$id",
'name' => $name,
);
The problem with this is that when I query for IDs, I need to use the following:
$query = Array( '_id' => "$id" );
instead of the more appropriate
$query = Array( '_id' => new MongoId("$id") );
forcing me to change all the queries. I thought that I do it by fixing the inserting, by putting '_id' => new MongoId("$id") but, if I use that, it will simply create the default
mongodb id, insead of my personalized one.
How can I fix this?
Thanks in advance
I am a little confused by exactly what you are asking for here, however, I believe I might just understand.
If you are using a _id different to the default ObjectId that MongoDB uses for the primary key of a row then you should not use ObjectId or in fact MongoId to create that object.
You should only use MongoId when you using the default _id that is provided, if you use your own the ObjectId (MongoId) will not function as you expect.
So the answer here is to stop using the MongoId.
Related
I am updating an old internal library to use PHP's PDO extension. In the old code, there's a function where the first parameter was a line of SQL and then the second parameter was an optional column to use as the key. I need to keep this same function signature so I don't break any code.
I'd like to use PDO's FETCH_UNIQUE fetch mode, but it would require me to parse every line of SQL that is passed in and add the key column to the beginning of the select. I'm worried that there are edge cases that I wouldn't think of that would break the call.
Is there another way in PDO to designate which column to use as the key when using PDO::FETCH_UNIQUE other than to add it directly to the column list in the SQL call?
Edit:
Here's some example code and more details:
$db = new Database();
$query = "first_name, last_name, contacts_id from contacts where first_name='George'";
$uniqueKeyField = "contacts_id";
$contact = $db->getRows($query, $uniqueKeyField);
Which would yield:
array (
[34] => array (
"first_name" => "George",
"last_name" => "Smith",
),
[452] => array (
"first_name" => "George",
"last_name" => "Johnson",
)
)
The problem is, I cannot always guarantee that the unique keyField will be first in the list like PDO requires because that was not a requirement of our API before.
After going through the manual, my guess is this is not possible to do with PDO::FETCH_UNIQUE and we will either have to use PDO::FETCH_ASSOC and loop through the results like we used to and build our own array or change every call to the above function in existing code to rearrange the fields so the unique keyfield is first. I was hoping someone knew of a way you could just pass the unique keyfield as an argument somewhere, but my guess is PDO faces the same problem we do - they have to have the keyfield in the query somewhere to pull out and put as the id in the returned array and they don't want to have to try to parse and add it to existing queries, thus the requirement to have it as the first field.
I have a converted ssp.class.php for PostgreSQL which works fine. However, I need to add ARRAY support to it.
I am hoping someone can give me some guidance/tips on the best way to do approach this, and/or give some example code if possible. I would appreciate it a lot.
You can get the modified file here: ssp.class.pg.php
About DataTables server side processing: https://datatables.net/examples/data_sources/server_side with an example.
I'm a little late to the party, but I found this question while searching google for an answer and wanted to post what I figured out to help the next person who might stumble upon this.
Note: I am using the referenced ssp.class.pg.php
My Solution - Use Heredoc
Using heredoc, you can better define your query using array functions, inner and outer joins, subqueries etc.
In my example, I have a PostgreSQL table that contains a jsonb column named properties. I want to select the value from the last_seen key.
Using Heredoc, I define my table as a query that will return the users last seen date value as a column.
$table = <<<EOT
(
SELECT
id,
unique_id,
properties->>'last_seen' as last_seen
FROM users
WHERE token = '$token'
) temp
EOT;
Then, I can define my columns for the SSP PG class using the returned columns from my table query.
$columns = array(
array( 'db' => 'id', 'dt' => 'id' ),
array( 'db' => 'unique_id', 'dt' => 'unique_id' ),
array( 'db' => 'last_seen', 'dt' => 'last_seen' ));
Finally, I'll use the defined variables to call the simple function.
$data_result = $ssp_pg->simple($request, $conn, $table, $primaryKey, $columns);
I'm trying to get the ID from mongodb to modify and delete user from a simple CRUD app with PHP and vue.js using axios
When I insert any user, I get this id.
{ "$oid": "5a8fd1ef1233610e40007667" }
I just need the ID that mongodb generate itself.
"5a8fd1ef1233610e40007667"
I'm using POST to get the ID and this is what I get when I use var_dump()
string(15) "[object Object]"
¿Any idea of how to get that ID? I've already tried several things, I hope you guys can help me
See the The MongoDB\BSON\ObjectId class.
In MongoDB, each document stored in a collection requires a unique _id field that acts as a primary key. If an inserted document omits the _id field, the driver automatically generates an ObjectId for the _id field.
specifically MongoDB\BSON\ObjectId::__toString, which returns the hexidecimal representation of the ObjectId. You can invoke __toString by casting the ObjectId to string, for example:
$stringID = (string)$objectID;
You do not need to create the ObjectID when you insert the record, for example (based on your comment)
$bulk = new MongoDB\Driver\BulkWrite();
$doc = [ 'firstname' => $firstname, 'lastname' => $lastname ];
$bulk->insert($doc);
$result = $manager->executeBulkWrite('db.collection', $bulk);
var_dump($result);
The mongo driver will create and set the '_id' field, insert takes the array by reference and can alter it.
I have a problem and i couldn't figure it out alone so I'm here because i really need some help D
I need to know if i can add a field with the same name, like, id, and id but with a diferente value
$usedWord = array('word' => $word);
// search for the word based on the array
$found = $collection->findOne($usedWord);
// If it returns
if (empty($found)) { // Here, it'll insert
$info = array('word'=> $word,
'id' => $id,
'path' => $path,
'start' => $startOfTheWord,
'end' => $endOfTheWord);
} else {
}
$collection->insert($info);
//disc from servidor
$conn->close();
On the Else part, i tried codes to add a new 'id', path and so on, the question is, can i create another 'id', 'patch' and so on OR i should create 'id1', path1 and so on ?
OBs:. i used $push and couldn't make it work =\
Not sure I got your question, but if you are sking about duplicate fields here what mongo docs says:
BSON documents may have more than one field with the same name. Most
MongoDB interfaces, however, represent MongoDB with a structure (e.g.
a hash table) that does not support duplicate field names. If you need
to manipulate documents that have more than one field with the same
name, see the driver documentation for your driver.
Anyway I think you should avoid duplicate fields in your documents it looks like there's something wrong with document structure design.
Ok, got this query (works fine, inserts an all...)
$db = Zend_Db_Table::getDefaultAdapter();
$data = array(
"comment_id" => new Zend_Db_Expr("nextval('comments_comment_id_seq')"),
"comment" => $comment,
"comment_level" => 1,
"is_active" => true,
"status" => 0,
"id" => $id,
"user_id" => $_SESSION['role']['user_id'],
"ts_create" => $created,
"ts_mod" => $created
);
$db->insert($this->_name, $data);
$newID = $db->lastInsertId();
I have even tried even
$newID = $db->insert($this->_name, $data);
And I can't get the ID's value. Its not mysql(i) so I think thats my first issue, as postgres doesn't appear to have an autoincriment in the way I am used to working with it atleast. So I am hoping someone here can help me out. Anyway to get the "comment_id" columns id, on a new inserted item? Cause right now I try lastInsertID and all I get is false or 1 which in either case is wrong.
Well GordonM pointed me in the direction of a specific document for zend, that reading through that, I was able to find what I needed. Unfortunately no one provided an actual answer. So I am going to answer my own question, for those who may stumble across it when they are stuck in a similar position as I just was.. But will give the up-vote to GordonM for getting me in the right direction. Thanks GordonM
Changing:
$newID = $db->insert($this->_name, $data);
To:
$newID = $db->lastSequenceId('comments_comment_id_seq');
From the Zend documentation, databases that use sequences to generate autoincrements (like Postgres) require you to specify the sequence by name in the lastInsertId() call.
Auto incremented fields are implemented as a sequence in PostgreSQL, the database reads from this sequence when inserting a new value. You have to use the name of that sequence when calling lastInsertId() to get the correct value.