Home > Software engineering >  MongoDB & PHP | How to add object into existing document?
MongoDB & PHP | How to add object into existing document?

Time:03-14

I am very new to MongoDB and PHP and I am trying to add an object into an already existing document. The problem is that I am seeing the $push variable being used a lot, but can't seem to get it working on my own project.

My Document

{
    "_id": {
        "$oid": "622dfd21f8976876e162c303"
    },
    "name": "testuser",
    "password": "1234"
}

Lets say this is a document inside my collection users. I want to add an object that is called domains with some data inside that object like below:

"domains": {
        "name": "example.com"
}

I have tried a bunch of different things, but they do not seem to work. What I tried: I have tried doing to like this:

$doc = array(
    "domains" => array("name": "nu.nl")
);

$collection->insert($doc);

And like this:

$insertOneResult = $collection->updateOne(
    {"name" : "testuser"},
    '$push': {"domains": {"name": "example.com"}}
); 

But they both do not work. Can anyone help me with this problem or comment a link which would help me with this problem? Thanks in advance!

CodePudding user response:

You were really close!

db.users.update({
  "name": "testuser"
},
{
  "$push": {
    "domains": {
      "name": "example.com"
    }
  }
})

Try it on mongoplayground.net.

I haven't used php since the ancient gforge days, but my guess at using the php connector would be (corrections welcome!):

<?php

$collection = (new MongoDB\Client)->test->users;

$updateResult = $collection->updateOne(
    ['name' => 'testuser'],
    ['$push' => ['domains' => ['name' => 'example.com']]]
);

printf("Matched %d document(s)\n", $updateResult->getMatchedCount());
printf("Modified %d document(s)\n", $updateResult->getModifiedCount());
  • Related