Question

I have a question about adding and removing value from a document. For example, I have a collection that looks like this:

{
    "_id" : ObjectId("537267b7186f521c07d63af1"),
    "users" : [ 
        "53725f9d186f521d07d63af1",
        "51725f9d186f521d07d33ah1"
    ]
}

I want to 1) remove "53725f9d186f521d07d63af1" from the users list, 2) add a new user to the list?

Thanks.

Was it helpful?

Solution

You can use $pull to remove 53725f9d186f521d07d63af1:

$collection->update(
  array('_id' => new MongoId('537267b7186f521c07d63af1')),   // _id of the document
  array('$pull' =>
    array('users' => new MongoId('53725f9d186f521d07d63af1') // id to be removed
  )
);

And $addToSet to add a new id:

$collection->update(
  array('_id' => new MongoId('537267b7186f521c07d63af1')),   // _id of the document
  array('$addToSet' =>
    array('users' => new MongoId('51725f9d186f521d07d33ah1') // id to be added
  )
);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top