1

I have a MongoDB collection, with documents that have an array field with objects. I need to delete a specific object when 2 properties match.

I've tried using pull https://laravel.com/docs/master/collections#method-pull

but it only allows me to remove the whole document property, or I'm using it wrong.

$node = Node::where('ports.number', $portNumber)->where('ports.ip', $portIp)->first();

Now I want to delete the port object inside the ports[] if the number and IP matches. Something like this, but with Eloquent:

if($ip && $number){
    unset($ports[$key])
}

Any comment appreciated.

2
  • please explain better your problem. You are getting a Node and you wrote you want to remove port object. What is the relationship between these two items? Commented Aug 22, 2019 at 15:03
  • sorry. Each node is a mongo document. Each node has an array field called ports, that possesses objects. I just need to delete one of those objects. I can handle the conditioning, but each attempt to remove only a single object from that array field, turned into deleting the whole document. I don't know if I make myself clear. Commented Aug 22, 2019 at 16:16

2 Answers 2

1

You can try this:

DB::collection('users')->where('name', 'John')->pull('messages', ['from' => 'Jane Doe', 'message' => 'Hi John']);

Hope it helps,

Sign up to request clarification or add additional context in comments.

Comments

0

Since the Node model does have (or should have) a one-to-many relationship with a Post model, you probably have this function in the Node model:

public function posts()
{
    return $this->hasMany('\App\Post', 'post_id');
}

Assuming that, to delete one record in the related model, you can access the model with the posts function, select the record/s you need and delete it/them.

With code:

// with ports() you get the related models of the Node
Node::ports()->where('number', $portNumber)->where('ip', $portIp)->delete();

2 Comments

I understand what you're saying, but it wasn't build that way, so to do that I'll have to change a lot, but it is a solution if there's no other way around. There's no Port model, ports exist as a JS object, saved inside a ports array, saved inside a Node document.
you can still create the models, they will not affect your website.

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.