Skip to content
Advertisement

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.

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 MongoDBClient('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!

Advertisement

Answer

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")]]
);
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement