PyMongo--非关系型数据库mongodb入门(3)
来源:未知 责任编辑:责任编辑 发表时间:2014-04-20 03:42 点击:次
39 else:
40 result = self.coll.find(query)
41 except NameError:
42 print 'some fields name are wrong in ',query
43 exit(0)
44 return result
45
46 def insert(self, data):
47 if type(data) is not dict:
48 print 'the type of insert data isn\'t dict'
49 exit(0) www.2cto.com
50 #insert会返回新插入数据的_id
51 self.coll.insert(data)
52
53 def remove(self, data):
54 if type(data) is not dict:
55 print 'the type of remove data isn\'t dict'
56 exit(0)
57 #remove无返回值
58 self.coll.remove(data)
59
60 def update(self, data, setdata):
61 if type(data) is not dict or type(setdata) is not dict:
62 print 'the type of update and data isn\'t dict'
63 exit(0)
64 #update无返回值
65 self.coll.update(data,{'$set':setdata})
66
67 if __name__ == '__main__':
68 connect = PyConnect('localhost', 27017)
69 connect.use('test_for_new')
70 connect.setCollection('collection1')
71 connect.insert({'a':10, 'b':1})
72 result = connect.find()
73 connect.update({'a':10, 'b':1}, {'b':10})
74 #x也是dict类型,非常好
75 for x in result:
76 if 'c' in x:
77 print x['_id'], x['a'], x['b'], x['c']
78 else: www.2cto.com
79 print x['_id'], x['a'], x['b']
80 connect.remove({'a':10})
4.9 补充:在调用self.conn[dbname]和self.db[collection].find(query)的时候要是能再加个存在性判断就好了,不然很容易出问题。
相关新闻>>
最新推荐更多>>>
- 发表评论
-
- 最新评论 更多>>