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

Time:03-16

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:[email protected]
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.

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!

CodePudding user response:

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")]]
);
  • Related