0

I have a document in mongodb that looks like this

{
   "_id": ObjectId("5378da275ad972a811c119fb"),
   "name": "test test",
   "fname": "test",
   "lname": "test",
   "phone": "13254355554",
   "user": "525518965ad972636d7aa0ae",
}

And i want to insert a new field for "employee_id" so the result should be exactly like this.

 {
   "_id": ObjectId("5378da275ad972a811c119fb"),
   "name": "test test",
   "fname": "test",
   "lname": "test",
   "employee_id": "09872",
   "phone": "13254355554",
   "user": "525518965ad972636d7aa0ae",
}

I have used $push and $addToSet but the results became an array like

"employee_id": {
     "0": "09872",
} 

2 Answers 2

1

Just use $set;

db.test.update(
      { _id:ObjectId("5378da275ad972a811c119fb") },    // Update this id only 
      { $set:{"employee_id": "09872"} }                // by setting employee_id
)
Sign up to request clarification or add additional context in comments.

Comments

1

Use the $set operator, $push and $addToSet are for arrays:

db.collection.update({}, {'$set': { "employee_id": "09872" } })

Comments

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.