gardni
gardni

Reputation: 1424

mongodb unwated removal of an empty field on update

Currently i run a mongo query that looks similar to the following:

$query = array(
    'user_id' => $this->getUserId(),
    'name'    => $this->getName()
);

I check to see if the record exists, if it does i want to update it, if not create it.

if(is_null($this->getId())) {
    $query['created'] = date('Y-m-d H:i:s');
    $this->collection->insert($query);
    $this->setId($query['_id']);
    return true;
} else {
    $conditions = array(
     '_id' => new \MongoId($this->getId())
    );
    return $this->collection->update($conditions, $query);
}

currently, if the record is new a 'created' date field is added. However when i run an update mongoDb appears to bring back the correct record but removing the created field, instead of just leaving it as it is.

Ive tried adding 'created' => $this->getCreated() to the $query and also to the $conditions, both proving unsuccessful. Is there something obvious im doing wrong thats causing the field i want left alone to delete?

Upvotes: 1

Views: 583

Answers (2)

Michael
Michael

Reputation: 231

Based off your problem, I would suggest re-trying "'created' => $this->getCreated() to the $query" provided your model has a created property defined, and your getter method is working, then this should use the current date on an insert, and the pre-set property value on update.

Upvotes: 2

Sammaye
Sammaye

Reputation: 43884

This is because of your $query value. It is a common beginner mistake.

Placing a whole query document into update like so:

$query = array(
    'user_id' => $this->getUserId(),
    'name'    => $this->getName()
);

Without any operators will actually REPLACE the original document with this one.

Instead to $set those fields to a new value you should use $set:

$query = array('$set' => array(
    'user_id' => $this->getUserId(),
    'name'    => $this->getName() )
);

This should give you the effect you desire.

Upvotes: 2

Related Questions