John Davidson

php - Modify mongodb cursor to add key of id and a given value

0 comments
Message:


I have this collection called rooms and i am querying it like this


<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);


require 'vendor/autoload.php';

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Max-Age: 1000");
header("Access-Control-Allow-Headers: X-Requested-With, Content-Type, Origin, Cache-Control, Pragma, Authorization, Accept, Accept-Encoding");
header("Access-Control-Allow-Methods: PUT, POST, GET, OPTIONS, DELETE");


$client = new MongoDB\Client("mongodb://localhost:27017");
$collection = $client->hotel->rooms;

/**
$cursor = $collection->find();
$id = '609d3999c4f94943dc2f9233';
$item = $collection->findOne(["_id" => new MongoDB\BSON\ObjectID($id)]);
*/
$cursor = $collection->find();

I would like to fetch the existing document id and use that id to insert a key of id and a value being the id of the document i looped


foreach ($cursor as $document) {

echo (string)$document["_id"].'<br/>';
/**
$key = (string)$document["_id"];
$data["$key"] = $document["property_name"];
*/
}

The above code outputs the id of the document.Since the cursor is iterable, i am doing this to convert it to json and sending it to Algolia.


echo json_encode(iterator_to_array($cursor));

However, i need a key called id to be able to set the objectid as algoloia only accepts a string for object id i.e


$index->saveObjects($data, ['objectIDKey' => 'id']);

How can i insert a key id with the value (string)$document["_id"] to the object i get from the cursor and encode it with the new key value that i inserted?.



My Answer:
php

// Connect to MongoDB
$mongo = new MongoDB\Driver\Manager("mongodb://localhost:27017");

// Query to get all rooms
$query = new MongoDB\Driver\Query([]);

// Execute query
$cursor = $mongo->executeQuery('database.rooms', $query);

// Modify cursor to add key of id and a given value
foreach ($cursor as $document) {
$document->id = '12345'; // Add key of id with value '12345'

// Print modified document
var_dump($document);
}

?>


In this code snippet, we are querying the `rooms` collection in the `database` database and then modifying the cursor to add a key of `id` with a given value of `12345` to each document in the cursor.

Rate this post

4 of 5 based on 4056 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us