0

This is my Object on mongoDB, I need to find the relations objects in the array by ID and remove it object.

 {
        "_id" : ObjectId("5b1a95c84700cb01758b4568"),
        "name" : "development",
        "type" : "",    
        "relations" : [ 
            {
                "_id" : ObjectId("5b1c290f20244eec02000029"),
                "name" : "mobile",
                "count" : 0
            }, 
            {
                "_id" : ObjectId("5b1c290f20244eec02000028"),
                "name" : "iOS",
                "count" : 0
            }
        ]
    }

What is the best way to find by relations object "_id" and then unset this object?

Here I am so getting ID

 $cursor = $collection->find([], ['relations' => []]);
 $find_id = "5b1c290f20244eec02000028";

        foreach (iterator_to_array($cursor) as $key) {
            foreach ($key['relations'] as $key2) {
                if ((string)$key2['_id'] == $find_id) {
                    var_dump($key2['_id']);
                }
            }
        }
Vahagn
  • 77
  • 1
  • 8
  • See also [`$pull`](https://docs.mongodb.com/manual/reference/operator/update/pull/) in the documentation. It's basically the top hit on a google search https://www.google.com/search?q=mongodb+remove+from+array – Neil Lunn Jun 09 '18 at 21:40
  • Thanks dear :) I did a poor search.. – Vahagn Jun 09 '18 at 21:46
  • but it didn't work.. Where am I wrong? `$collection->update( [], ['$pull' => ['relations' => ["_id" => new MongoId('5b1c290f20244eec02000028')] ]], ["multi" => true] );` – Vahagn Jun 09 '18 at 22:59
  • You appear to be reading old documentation. `new MongoDB\BSON\ObjectId` is where the `ObjectId` method resides in modern drivers. – Neil Lunn Jun 09 '18 at 23:10
  • I tried in many ways.. even I copied from this [link](https://stackoverflow.com/questions/16959099/how-to-remove-array-element-in-mongodb) which you indicated (db and answer) tried but does not work.. `$set` and `$unset` working but `$pull` does not work at all... my mongodb version is `v3.4.7` and I work in the local – Vahagn Jun 09 '18 at 23:21
  • Please think for a moment Hundreds of Thousands if not millions of people use this all the time `db.collection.update({}, { "$pull": { "relations": { "_id": ObjectId("5b1c290f20244eec02000028") } } })` works just fine and removes the element from your document as listed in the question. Read the documentation, use the shell to practice from samples there and then look at your code and apply the correct options. You need the correct `ObjectId` type in order to match an `ObjectId`. – Neil Lunn Jun 09 '18 at 23:26
  • Ok, thank you very much )) – Vahagn Jun 09 '18 at 23:27

0 Answers0