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.
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 am currently learning MongoDB. I have seen tutorials for querying a field in a collection. I would like to know how to query in PHP using the MongoId Object _id value. The closest answer to my question is at Perl Mongo find object Id .
Also, is there a way that when a new record is created, the Object _id value can be recorded in another field of that record?
Thanks.
Update:
In addition to the answer I chose below, a coworker found this as well:
mongodb php findone() by ID
This should help, from the mongodb web site (http://blog.mongodb.org/post/26903435041/mongodb-for-the-php-mind-part-2):
// This is only a string, this is NOT a MongoId
$mongoid = '4cb4ab6d7addf98506010000';
// You will not find anything by searching by string alone
$nothing = $collection->find(array('_id' => $mongoid));
echo $nothing->count(); // This should echo 0
// THIS is how you find something by MongoId
$realmongoid = new MongoId($mongoid);
// Pass the actual instance of the MongoId object to the query
$something = $collection->find(array('_id' => $realmongoid));
echo $something->count(); // This should echo 1
Regarding part of your question, I'm not aware of any automated way to store the objectid in another field but I'm also not aware of why you would want to do that - you already have it stored in _id, why would you want it in another field?
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.
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.
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