MantyQ2341414514
MantyQ2341414514

Reputation: 77

How to $push to an array MongoDB PHP driver

I current have a database with the following document:

{"_id":"5d9bd9429303fc05f0651ff2",

"userID":"2",

"email":"[email protected]",

"password":"admin",

"dob":"1990-12-06",

"firstName":"AdminFirst",

"lastName":"AdminLast",

"screenName":"The Admin",

"gender":"m",

"status":"status",

"location":"location",

"visibility":"e",

"friends":[""],

"friendRequests":[""]}

I am connecting to the MongoDB through PHP, with the following code:

    //connect to the client
$client = new MongoDB\Client("mongodb://localhost:27017");
//Connect to the specific collection
$collection = $client->FBLite->Users;
//Specific user document, stored in session.
$user = $_SESSION['currentDocument'];

I am trying to $push a string value into the "friends" array of one of my documents. What would be the correct way to do this via PHP?

I have tried:

$addFriend = update(array('$push'=> array("friends","4"));)

and:

$collection->update(['userID'] => 2, '')

However neither of these will work, and PHP will not throw any errors for me to read.

Upvotes: 0

Views: 367

Answers (1)

MantyQ2341414514
MantyQ2341414514

Reputation: 77

This was done with the following:

$collection->updateOne(
    ['userID' => '2'],
    ['$push' => ['friends' => '55']]
  );

Will push the value "55" to the object with userID '2'

Upvotes: 1

Related Questions