12-12 04:59
Notice
Recent Posts
Recent Comments
관리 메뉴

Scientific Computing & Data Science

[MongoDB] Updating Documents by Document Replacement 본문

Data Science/MongoDB

[MongoDB] Updating Documents by Document Replacement

cinema4dr12 2014. 1. 19. 17:18

Written by cinema4d

우선 다음과 같이 데이터를 준비하도록 하자:

// user DB "foobar"
use foobar

// define user1
var user1 = {"username" : "gchoi"}
user1.age = 37
user1.relationships = {"friends" : 100, "enemies" : 1}

// define user2
var user2 = {"username" : "tjkwak"}
user3.age = 31
user2.relationships = {"friends" : 50, "enemies" : 5}

// define user3
var user3 = {"username" : "jmpark"}
user3.age = 25
user3.relationships = {"friends" : 10, "enemies" : 3}

// define user4
var user4 = {"username" : "jhlee"}
user4.age = 37
user4.relationships = {"friends" : 1, "enemies" : 300}

// insert users into "users" collection of DB "foobar"
db.users.insert(user1)
db.users.insert(user2)
db.users.insert(user3)
db.users.insert(user4)

// show stat of DB we are using
db.stats()


여러분의 명령 쉘에서 현재 상태는 다음과 같을 것이다:

> db.stats()
{
	"db" : "foobar",
	"collections" : 3,
	"objects" : 8,
	"avgObjSize" : 77,
	"dataSize" : 616,
	"storageSize" : 16384,
	"numExtents" : 3,
	"indexes" : 1,
	"indexSize" : 8176,
	"fileSize" : 201326592,
	"nsSizeMB" : 16,
	"dataFileVersion" : {
		"major" : 4,
		"minor" : 5
	},
	"ok" : 1
}


Update를 위해 다음과 같이 입력하자:

// store userdate with username "jhlee"
var temp = db.users.findOne({"username" : "jhlee"})
// increment the user's age by 1
temp.age++
// display the current age on terminal
temp.age
// update the user with username "jhlee" with temp
db.users.update({"username" : "jhlee"}, temp)
// show users collection
db.users.find()


Comments