Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

MongoDB & PHP | How to add into object that is inside an array?

I am new to MongoDB and PHP and I am trying to make an API. The current problem I have is that I am not able to add an array into an object that is inside an array (of objects). I have tried a lot, but all failed.

This is the document I have so far:

_id:62307ccecabc9c2a2c4563e3
username:"NEWUser"
email:user@mail.com
password:1234
level:1
domainArray:Array
  0:Object
     domainname:"example.com"
     domainvalue:4
  1:Object
     domainname:"facebook.com"
     domainvalue:3

I would like to add an array after domainvalue, but can’t seem to do that.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My code:

   public function postDomain($domainData){//add user and replace it with testuser
        $data = json_decode(file_get_contents("php://input"), true);
        $collection = $collection = (new MongoDB\Client('mongodb://localhost:27017'))->mydb->users;
        $insertOneResult = $collection->updateOne(
            ["username" => "NEWUser"],
            ['$push' =>["domainArray" => $data]]
        );
    }

The $data variable:

{
    "domainname":"twitter.com",
    "domainvalue":2
}

How would I change this code so that there is an array added after domainvalue?
I have tried doing things like this:

$insertOneResult = $collection->updateOne(
    ["username" => "NEWUser", "domainArray"],
    ['$push' => ["domainname.$.ouputArray" => array("outputArray")]]
);

But without any luck. Can someone please help me because I am really stuck with this problem.
Thanks in advance!

>Solution :

To create a new field for the nested documents in an array, you need the $set operator and $[] all positional operator.

db.collection.update({
  "username": "NEWUser"
},
{
  "$set": {
    "domainArray.$[].ouputArray": []  // Array
  }
})

Sample Mongo Playground

While for PHP syntax:

$insertOneResult = $collection->updateOne(
    ["username" => "NEWUser"],     
    ['$set' => ["domainArray.$[].ouputArray" => array("outputArray")]]
);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading