1

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!

1 Answer 1

1

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());
Sign up to request clarification or add additional context in comments.

5 Comments

How would that look in PHP, since I need to do it in that language?
@Coder See answer update for my guess at php.
I have one more question. What if I want to add an object within the domain object now (so adding an object within an object that is in a document), how would I do that? I cannot seem to figure it out
@Coder Probably best to ask a new question showing the doc before/after with what you've tried.
Did it! Thanks for the tip!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.