Change the `_id` field name and value

I have pulled the MongoDB documents into a PHP array variable. I need to covert this to a JS array variable instead, with some changes to the array structure to:

  • rename the _id field / key to “value”
  • change the value of _id to a simple string
  • rename the “name” field / key to “text”

This is because my use case is to pass the JS array into the Slim Select JS library, which allows me to pass in a data array in this format to add items to the <select> element:

var jsPlayers2 = [
	{"placeholder": true, "text": "Type Name"},
	{"text": "Leo Messi", "value": "sdfhkj29dfaj"},
	{"text": "Joe Bloggs", "value": "ajdsfh438yca22"},
	{"text": "Jane Doe", "value": "abc3"}
];

I use the PHP json_encode($players) function for the conversion between languages. The current format of my JS array is:

{_id: {$oid: "609d0993906429612483cfb1"}, name: "Jane Doe"}

Can I do this in PHP (before) or JS (after) the conversion?

I resolved this in a PHP loop as follows to change the array structure as my JS library required:

foreach($players as $player) {
		$player["value"] = (string) $player['_id'];
		$player["text"] = $player["name"];
		unset($player["clubs"]);
		unset($player["_id"]);
		unset($player["name"]);
}

you may want to do this on the server side:

const aggregation = [
  {
    $addFields: { value: { $toString: "$_id" }, text: "$name" }
  },
  {
    $project: { _id:0, value:1, text:1 }
  }
];

db.yourcollection.aggregate(aggregation);

this one is in javascript/mongo shell format. edit/change it as required to PHP :slight_smile:

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.