05-05 22:05
Notice
Recent Posts
Recent Comments
관리 메뉴

Scientific Computing & Data Science

[MongoDB] Update Modifiers / Part. 2 - $set / $unset 본문

Data Science/MongoDB

[MongoDB] Update Modifiers / Part. 2 - $set / $unset

cinema4dr12 2014. 1. 19. 19:25

Written by cinema4d

Update items using "$set" modifier :

"$set" modifier adds item(s) if the relevant key exists or creates the key when absent.

 

Type the following for data preparation:

// drop the current database
db.dropDatabase()

// define webpage1
var user1 = {"username" : "gchoi", "age" : 37, "sex" : "male"}

// insert items into DB
db.users.insert(user1)
db.users.find()

 

Result:

> db.users.find() { "_id" : ObjectId("52dba60d0ea42add16dec853"), "username" : "gchoi", "age" : 37, "sex" : "male" }


Type the following to create "favorite food" key:

// update(create "favorite food" key)
db.users.update({"username" : "gchoi"}, {"$set" : {"favorite food" : "김치볶음밥"}})
db.users.find()


Result:

> db.users.find() { "_id" : ObjectId("52dba60d0ea42add16dec853"), "age" : 37, "favorite food" : "김치볶음밥", "sex" : "male", "username" : "gchoi" }


Set "favorite food" as an array type:

db.users.update({"username" : "gchoi"}, {"$set" : {"favorite food" : ["돼지갈비", "삼겹살", "된장찌개"]}})


Result:

> db.users.find() { "_id" : ObjectId("52dbdd7aa1c05d0be00a4b63"), "age" : 37, "favorite food" : [  "돼지갈비",  "삼겹살",  "된장찌개" ], "sex" : "male", "username" : "gchoi" }


Now we use "$unset" to remove the key "favorite food" to return to the beginning as we type the following:

// remove "favorite food"
db.users.update({"username" : "gchoi"}, {"$unset" : {"favorite food" : 1}})


Result:

> db.users.find() { "_id" : ObjectId("52dbdd7aa1c05d0be00a4b63"), "age" : 37, "sex" : "male", "username" : "gchoi" }


Comments