日期:2014-05-16  浏览次数:20527 次

mongodb实践 2

接上一篇:

?

#删除数据

?

*删除某条数据@

> db.things.remove({i:1});

		> db.things.find({i:1});
		> db.things.find({i:2});
		{ "_id" : ObjectId("4ee8510a0c16000000006ec7"), "i" : 2, "i2" : 4 }
		{ "_id" : ObjectId("4ee8514d0c16000000006edb"), "i" : 2, "i2" : 4, "i3" : 8 }
?

db.things.remove()会删除things聚集中的所有数据。

甚至可以删除聚集本身@

db.things.drop()

?

#更新数据

?

*mongodb官方建议,如果仅仅是更改某些域,那么使用$modifiers 更加合适~

写道

a modifier update has the advantages of avoiding the latency involved in querying and returning the object.
The modifier update also features operation atomicity and very little network data transfer.
?

*modifiers有如下操作@

写道

$inc 自增/自减
$set 赋值
$unset 删除某个列
$push 追加到原有值后
$pushAll 追加数组到原有值后
$addToSet and $each 向数组添加一个元素/向数组添加多个元素
$pop 移除某个数组元素(-1表示第一个、1表示最后一个)
$pull 移除指定的数组元素
$pullAll 移除多个指定的数组元素
$rename 更新域名
$bit 按位操作,仅限整型
?

*将客户joy的年龄+1@

> db.customers.find({name:"joy"});

		{ "_id" : ObjectId("4ee98be10b240000000027f3"), "name" : "joy", "age" : 22 }
		> db.customers.update({name:"joy"},{$inc:{age:1}});
		> db.customers.find({name:"joy"});
		{ "_id" : ObjectId("4ee98be10b240000000027f3"), "name" : "joy", "age" : 23 }
?

再添加两条数据@

db.customers.save({name:"joy",age:23});db.customers.save({name:"joy",age:23});

?

如何将所有joy的年龄都变为24呢?

试一下前面的方法@

> db.customers.update({name:"joy"},{$inc:{age:1}});

		> db.customers.find({name:"joy"});
		{ "_id" : ObjectId("4ee98be10b240000000027f3"), "name" : "joy", "age" : 24 }
		{ "_id" : ObjectId("4ee99ce18b12000000004f86"), "name" : "joy", "age" : 23 }
		{ "_id" : ObjectId("4ee99d0f8b12000000004f87"), "name" : "joy", "age" : 23 }
?

很遗憾只改变了第一条数据:(

update的语法为:db.customers.update(query, object[, upsert_bool, multi_bool])

?,有两个可选参数,我们没有用到,官网上对这几个参数的解释是@

写道

query 查询哪些记录需要被更新
object 需要更新的域
upsert 如果为true则有记录时更新记录,没有记录时添加一条新记录(默认值似乎是true)
multi 决定到底是更新所有查询到的记录还是只更新一条(默认值似乎是false)
?

再试一下@

> db.customers.update({name:"joy"},{$inc:{age:1}},true,true);

		> db.customers.find({name:"joy"});
		{ "_id" : Obj