Jonathan Thurft
Jonathan Thurft

Reputation: 4173

Update collection erases all information inside

I am new to MongoDB and trying to perform my first updates.

I have my users collection that is populated by an insert statement. Now, I want to add or insert the field authCode with some data into a specific user.

My problem is that when I perform the following function the whole user data becomes replaced by the information in that update statement. My understanding is that by using upsert I would insert or update a users collection. given that the user already exist I expect just the authCode field to be created or updated.

Could anyone point out what am i doing wrong?

public function addAuthCode( array $userId, $code ) {
        $user = $this->db()->user;
        $user->update(
                    $userId,
                    array( 'authCode' => $code ),
                    array( 'upsert' => true, 'safe' => true )
                    );
    }

Upvotes: 0

Views: 30

Answers (1)

Chris Chang
Chris Chang

Reputation: 426

You'll want to take a look at the MongoDB documentation for updates found here: http://docs.mongodb.org/manual/reference/method/db.collection.update/#db.collection.update

Specifically:

Add New Fields

db.bios.update(
   { _id: 3 },
   { $set: {
             mbranch: "Navy",
             "name.aka": "Amazing Grace"
           }
   }
)

Notice that in order to add a field, you need to use the $set operator

Chris@MongoLab

Upvotes: 2

Related Questions