日期:2014-05-16 浏览次数:20502 次
接上篇,这里主要介绍利用Mongodb的cli对集合中的记录进行增删改查的操作,简单地说,就是Record级别上进行的操作。
从这里开始,我们用事先存在的(上)中提到的blogtest数据库做测试,其中有两个Collection,一个是book,另一个是user。
1 插入操作
1.1 向user集合中插入两条记录 > db.user.insert({'name':'Gal Gadot','gender':'female','age':28,'salary':11000}) > db.user.insert({'name':'Mikie Hara','gender':'female','age':26,'salary':7000}) 1.2 同样也可以用save完成类似的插入操作 > db.user.save({'name':'Wentworth Earl Miller','gender':'male','age':41,'salary':33000})
2 查找操作
2.1 查找集合中的所有记录
> db.user.find() { "_id" : ObjectId("52442736d8947fb501000001"), "name" : "lfqy", "gender" : "male", "age" : 23, "salary" : 15 } { "_id" : ObjectId("52453cfb25e437dfea8fd4f4"), "name" : "Gal Gadot", "gender" : "female", "age" : 28, "salary" : 11000 } { "_id" : ObjectId("52453d8525e437dfea8fd4f5"), "name" : "Mikie Hara", "gender" : "female", "age" : 26, "salary" : 7000 } { "_id" : ObjectId("52453e2125e437dfea8fd4f6"), "name" : "Wentworth Earl Miller", "gender" : "male", "age" : 41, "salary" : 33000 } { "_id" : ObjectId("52454155d8947fb70d000000"), "name" : "not known", "sex_orientation" : "male", "age" : 13 }2.2 查找集合中的符合条件的记录
(1)单一条件 a)Exact Equal: 查询age为了23的数据 > db.user.find({"age":23}) { "_id" : ObjectId("52442736d8947fb501000001"), "name" : "lfqy", "gender" : "male", "age" : 23, "salary" : 15 } b)Great Than: 查询salary大于5000的数据 > db.user.find({salary:{$gt:5000}}) { "_id" : ObjectId("52453cfb25e437dfea8fd4f4"), "name" : "Gal Gadot", "gender" : "female", "age" : 28, "salary" : 11000 } { "_id" : ObjectId("52453d8525e437dfea8fd4f5"), "name" : "Mikie Hara", "gender" : "female", "age" : 26, "salary" : 7000 } { "_id" : ObjectId("52453e2125e437dfea8fd4f6"), "name" : "Wentworth Earl Miller", "gender" : "male", "age" : 41, "salary" : 33000 } c)Fuzzy Match 查询name中包含'a'的数据 > db.user.find({name:/a/}) { "_id" : ObjectId("52453cfb25e437dfea8fd4f4"), "name" : "Gal Gadot", "gender" : "female", "age" : 28, "salary" : 11000 } { "_id" : ObjectId("52453d8525e437dfea8fd4f5"), "name" : "Mikie Hara", "gender" : "female", "age" : 26, "salary" : 7000 } { "_id" : ObjectId("52453e2125e437dfea8fd4f6"), "name" : "Wentworth Earl Miller", "gender" : "male", "age" : 41, "salary" : 33000 } 查询name以G打头的数据 > db.user.find({name:/^G/}) { "_id" : ObjectId("52453cfb25e437dfea8fd4f4"), "name" : "Gal Gadot", "gender" : "female", "age" : 28, "salary" : 11000 } (2)多条件"与" 查询age小于30,salary大于6000的数据 > db.user.find({age:{$lt:30},salary:{$gt:6000}}) { "_id" : ObjectId("52453cfb25e437dfea8fd4f4"), "name" : "Gal Gadot", "gender" : "female", "age" : 28, "salary" : 11000 } { "_id" : ObjectId("52453d8525e437dfea8fd4f5"), "name" : "Mikie Hara", &quo