Basic operations for MongoDB in Python: connect and query instances

  • 2020-04-02 14:36:52
  • OfStack

MongoDB is a database based on distributed file storage. Written by the C++ language. Designed to provide WEB applications with scalable, high-performance data storage solutions. It is characterized by high performance, easy to deploy, easy to use, storage of data is very convenient.

MongoDB is simple to use

Join database


In [1]: import pymongo
In [2]: from pymongo import Connection
In [3]: connection = Connection('192.168.1.3', 27017) //Create a join

Connection related parameters


Connection([host='localhost'[, port=27017[, pool_size=None[, auto_start_request=None[, timeout=None[, slave_okay=False[, network_timeout=None[, document_class=dict[, tz_aware=True]]]]]]]]])

Database operation


In [9]: c.database_names() //Lists all database names
Out[9]: [u'test', u'admin', u'yuhen', u'sms', u'local'] In [10]: c.server_info() //View server-related information
Out[10]:
{u'bits': 64,
 u'gitVersion': u'nogitversion',
 u'ok': 1.0,
 u'sysInfo': u'Linux yellow 2.6.24-27-server #1 SMP Fri Mar 12 01:23:09 UTC 2010 x86_64 BOOST_LIB_VERSION=1_40',
 u'version': u'1.2.2'} In [16]: db = c['test'] //Select database
In [17]: db.collection_names() //Lists all collection names in the current database
Out[17]: [u'system.indexes', u'fs.files', u'fs.chunks', u'test_gao'] In [23]: db.connection //View the join information
Out[23]: Connection('192.168.1.3', 27017) In [24]: db.create_collection('test_abeen') //Create a new collection
Out[24]: Collection(Database(Connection('192.168.1.3', 27017), u'test'), u'test_abeen') In [25]: db.last_status() //Check the last operation status
Out[25]: {u'err': None, u'n': 0, u'ok': 1.0} In [26]: db.name //View the current database name
Out[26]: u'test' In [27]: db.profiling_info() //View the configuration information
Out[27]: [] In [28]: db.profiling_level()
Out[28]: 0.0

Set operations


In [31]: db.collection_names() //View the current database for all collection names
Out[31]:
[u'system.indexes',
 u'fs.files',
 u'fs.chunks',
 u'test_gao',
 u'system.users',
 u'test_abeen'] In [32]: c = db.test_abeen //Select set
In [33]: c.name //View the current collection name
Out[33]: u'test_abeen' In [35]: c.full_name //View the full name of the current collection
Out[35]: u'test.test_abeen'
In [36]: c.database //View the current collection database information
Out[36]: Database(Connection('192.168.1.3', 27017), u'test') In [38]: post = {"author":"Mike","text":"this is a test by abeen"}
In [39]: posts = db.posts
In [40]: posts.insert(post) //Insert the document into the database collection, and by default create the collection
Out[40]: ObjectId('4c358492421aa91e70000000')
In [41]: db.collection_names() //Displays all collection names
Out[41]:
[u'system.indexes',
 u'fs.files',
 u'fs.chunks',
 u'test_gao',
 u'system.users',
 u'test_abeen',
 u'posts'] In [42]: posts.find_one() //Find information from the collection
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"}})//Update collection document information
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"}) //Delete qualified documents
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") //Delete the collection
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']

code


In [113]: result = db.posts.find({"a":"aa"})//Find the < br / > 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'}]

The find format


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

code


In [120]: db.posts.count()//Current collection document number
Out[120]: 3
In [121]: type(db.posts)
Out[121]: <class 'pymongo.collection.Collection'> In [138]: posts.rename('test_abeen')//Rename the current collection
In [139]: db.collection_names()
Out[139]:
[u'system.indexes',
 u'fs.files',
 u'fs.chunks',
 u'test_gao',
 u'system.users',
 u'test_abeen'] In [151]: for post in c.find({"a":"aa"}).sort("a"): //Query the side-by-side sequence
    post
Out[152]: {u'_id': ObjectId('4c358ad4421aa91e70000002'), u'a': u'aa', u'b': u'bb'}
Out[152]: {u'_id': ObjectId('4c358ad9421aa91e70000003'), u'a': u'aa', u'b': u'bb'}


> db.foo.insert( { x : 1, y : 1 } )
> db.foo.insert( { x : 2, y : "string" } )
> db.foo.insert( { x : 3, y : null } )
> db.foo.insert( { x : 4 } ) //Query #1 y is null or does not exist
> db.foo.find( { "y" : null } )
{ "_id" : ObjectId("4dc1975312c677fc83b5629f"), "x" : 3, "y" : null }
{ "_id" : ObjectId("4dc1975a12c677fc83b562a0"), "x" : 4 } //Query #2 y is null
> db.foo.find( { "y" : { $type : 10 } } )
{ "_id" : ObjectId("4dc1975312c677fc83b5629f"), "x" : 3, "y" : null } //Query #3: result that y does not exist
> db.foo.find( { "y" : { $exists : false } } )
{ "_id" : ObjectId("4dc1975a12c677fc83b562a0"), "x" : 4 }


Related articles: