Python中的MongoDB基本操作:连接、查询实例

2019-10-05 08:43:57丽君

 u'system.users',
 u'test_abeen',
 u'posts']

In [42]: posts.find_one() //从集合查找信息
Out[42]:
{u'_id': ObjectId('4c358492421aa91e70000000'),
 u'author': u'Mike',
 u'text': u'this is a test by abeen'}
In [52]: p.update({"author":"Mike"},{"$set":{"author":"abeen","text":"this is a test by abeen shan shan"}})//更新集合文档信息
In [55]: list(p.find())
Out[55]:
[{u'_id': ObjectId('4c358492421aa91e70000000'),
  u'author': u'abeen',
  u'text': u'this is a test by abeen shan shan'}]

In [96]: list(posts.find())
Out[96]:
[{u'_id': ObjectId('4c358492421aa91e70000000'),
  u'author': u'Mike',
  u'text': u'this is a test by abeen'},
 {u'_id': ObjectId('4c358ad4421aa91e70000002'), u'a': u'aa', u'b': u'bb'},
 {u'_id': ObjectId('4c358ad9421aa91e70000003'), u'a': u'aa', u'b': u'bb'},
 {u'_id': ObjectId('4c358abb421aa91e70000001'),
  u'a': u'abeen',
  u'b': u'this bb is updated'}]
In [97]: posts.remove({"a":"abeen"}) //删除符合条件的文档
In [98]: list(posts.find())
Out[98]:
[{u'_id': ObjectId('4c358492421aa91e70000000'),
  u'author': u'Mike',
  u'text': u'this is a test by abeen'},
 {u'_id': ObjectId('4c358ad4421aa91e70000002'), u'a': u'aa', u'b': u'bb'},
 {u'_id': ObjectId('4c358ad9421aa91e70000003'), u'a': u'aa', u'b': u'bb'}]

In [102]: db.collection_names()
Out[102]:
[u'system.indexes',
 u'fs.files',
 u'fs.chunks',
 u'test_gao',
 u'system.users',
 u'test_abeen',
 u'posts',
 u'doc_abeen']

In [104]: db.drop_collection("doc_abeen") //删除集合
In [105]: db.collection_names()
Out[105]:
[u'system.indexes',
 u'fs.files',
 u'fs.chunks',
 u'test_gao',
 u'system.users',
 u'test_abeen',
 u'posts']

代码

In [113]: result = db.posts.find({"a":"aa"})//查找
In [114]: type(result)
Out[114]: <class 'pymongo.cursor.Cursor'>
In [119]: list(result)
Out[119]:
[{u'_id': ObjectId('4c358ad4421aa91e70000002'), u'a': u'aa', u'b': u'bb'},
 {u'_id': ObjectId('4c358ad9421aa91e70000003'), u'a': u'aa', u'b': u'bb'}]

find格式

find([spec=None[, fields=None[, skip=0[, limit=0[, timeout=True[, snapshot=False[, tailable=False[, sort=None[, max_scan=None[, as_class=None[, **kwargs]]]]]]]]]]])

代码

In [120]: db.posts.count()//当前集合文档数
Out[120]: 3
In [121]: type(db.posts)
Out[121]: <class 'pymongo.collection.Collection'>

In [138]: posts.rename('test_abeen')//重命名当前集合
In [139]: db.collection_names()
Out[139]:
[u'system.indexes',
 u'fs.files',