Python Learning database: MongoDB

Source: Internet
Author: User
Tags prev

Reference URL:

1, http://www.runoob.com/mongodb/mongodb-intro.html

2, http://www.runoob.com/python/python-mysql.html

3, http://www.cnblogs.com/descusr/archive/2011/11/15/2249391.html

From Pymongo Import * # Guide Package con = Connection (...) # link db = con.database # link database db.authenticate (' username ', ' password ') # login D B.drop_collection (' users ') #删除表db. Logout () # Exit Db.collection_names () # View all Tables Db.users.count () # Number of Queries Db.users.find_one ( {' name ': ' Xiaoming '}) # Single Object Db.users.find ({' Age ': 18}) # All objects db.users.find ({' id ': 1, ' _id ': 0}) # returns some fields the default _id always returns 0 does not return 1 returns db.users. Find ({}). Sort ({' Age ': 1}) # sorts Db.users.find ({}). Skip (2). Limit (5) # Slice

Db.users.find ({}, {}, 10, 20) # The second notation slice is not tested

Collection

Properties: Full_name,name,databaseinsert (Self, doc_or_docs, manipulate=true, Safe=false, Check_keys=true, **kwargs):
    • When Manipulate=true, _id is automatically added to Dict and returns some _id (or list (_id)).
      is False, None is returned
    • When safe is true, the To_save is automatically judged to be dict, and if an error is checked, an error message is prompted, waiting for the database to respond without executing the INSERT database
    • Doc_or_docs allows one or more records to be inserted
Save (self, to_save, manipulate=true, Safe=false, **kwargs)
    • To_save, accept only one dict (dictionary)
    • When the to_save contains _id, it is update (may update more than one)
Drop (self)
    • Delete some collection (collection and data deleted together)
Remove (self, spec_or_id=none, Safe=false, **kwargs)
    • Romve a record
    • Delete operation is not reversible
    • When safe is true, the correctness of the parameter is automatically determined and, if there is an exception, waits for the database to respond without performing a delete operation
    • SPEC_OR_ID, for a complete doc or a dictionary with _id specified
Find_one (self, spec_or_id=none, *args, **kwargs)
    • SPEC_OR_ID, for a complete doc or a dictionary with _id specified
    • Returns a record that matches a condition
Find (self, *args, **kwargs)
    • Parameter must be a doc prototype (eg:{"name": "ABC"})
    • Returns the Cursor, not (Result collection)
    • Spec Query conditions
    • Fields returns the field list, but _id is returned by default
    • The number of records omitted by skip
    • Maximum number of records returned by limit at a time
    • Timeout If true, the time-out will automatically break
    • Snapshot snapshot mode, True to ensure that return results are not duplicated
    • Tailable keeps the tailable cursor open and records the last bit
    • Sort sorted Field
    • Max_scan maximum number of allowed queries (version **>= 1.5.1**)
    • AS_CLASS Specifies the type of query result, which defaults to ~pymongo.connection.connection.document_class
    • Network_timeout specifying the time-out period
COUNT (self) Returns the total number of records create_index (self, key_or_list, Deprecated_unique=none, ttl=300, **kwargs)
    • Create an index for one or more keys
    • Key must be a string type
    • Eg:create_index ("Mike")
    • Eg:create_index (["Mike", Pymongo. Descending), ("Eliot", Pymongo. Ascending)])
Ensure_index (self, key_or_list, Deprecated_unique=none, ttl=300, **kwargs)
    • Checks if there are any indexes, creates if not present, returns none
Drop_indexes (self) is deleted so index drop_index (self, index_or_name) deletes the specified index index_information (self) Returns the index information rename (self, new_name, **kwargs) re-points to a collectiondistinct (self, key) to return all key records that are not duplicates

Mongo–path

Db. AddUser (username,password) Add user

Db.auth (Usrename,password) setting Up Database connection validation

Db.clonedatabase (fromhost) cloning a database from the target server

DB.COMMANDHELP (name) returns the Help for the command

Db.copydatabase (fromdb,todb,fromhost) Copy database fromdb-source database name, todb-target database name, fromhost-source database server address

Db.createcollection (name,{size:3333,capped:333,max:88888}) creates a data set that is equivalent to a table

Db.currentop () cancels the current operation of the current library

Db.dropdatabase () Delete the current database

Ten Db.eval (Func,args) Run code server-side

One db.getcollection (CNAME) gets a data set, same usage: db[' cname '] or db.cname

Db.getcollenctionnames () Gets a list of all data collection names

Db.getlasterror () returns the last Error prompt message

Db.getlasterrorobj () returns the last Error object

Db.getmongo () Gets the connection object of the current server get the server connection object

Db.getmondo (). Setslaveok () Allow this connection to the read from then Nonmaster membr of a replica pair

Db.getname () returns the name of the operation database

Db.getpreverror () returns the previous Error object

Db.getprofilinglevel ()? What level

Db.getreplicationinfo ()? What information

DB.GETSISTERDB (name) get the db at the same server as this onew

Db.killop () Stop (kill) The current operation in the current library

Db.printcollectionstats () returns the current library's dataset status

Db.printreplicationinfo ()

Db.printslavereplicationinfo ()

Db.printshardingstatus () returns whether the current database is a shared database

Db.removeuser (username) Delete User

Db.repairdatabase () repairing the current database

Db.reseterror ()

Db.runcommand (cmdobj) run a database command. If Cmdobj is a string, turns it into {cmdobj:1}

Db.setprofilinglevel (level) 0=off,1=slow,2=all

Db.shutdownserver () Close the current service program

Db.version () returns the version information of the current program

34

Db.linlin.find ({id:10}) returns the DataSet id=10 the Linlin dataset

Db.linlin.find ({id:10}). Count () returns the total number of data id=10 the Linlin dataset

PNs Db.linlin.find ({id:10}). Limit (2) returns the DataSet from the second data set id=10 the dataset of the Linlin dataset

Db.linlin.find ({id:10}). Skip (8) returns the dataset from 0 to eighth for the DataSet id=10 the Linlin dataset

Db.linlin.find ({id:10}). Limit (2). Skip (8) Returns the data from the second to eighth data sets id=1= the dataset of the Linlin dataset

Db.linlin.find ({id:10}). Sort () returns the sorted data set id=10 the Linlin dataset

Db.linlin.findOne ([query]) returns an eligible piece of data

Db.linlin.getDB () returns the name of the database to which this dataset belongs

Db.linlin.getIndexes () returns the index information for some datasets

Db.linlin.group ({key:...,initial:...,reduce: ... [, cond: ...]})

Db.linlin.mapReduce (Mayfunction,reducefunction,

46)

Db.linlin.remove (query) deletes a single piece of data in a data set

Db.linlin.renameCollection (newName) Rename some data set names

Db.linlin.save (obj) inserting a single piece of data into the data set

Db.linlin.stats () Returns the state of this dataset

Wuyi Db.linlin.storageSize () returns the storage size of this dataset

Db.linlin.totalIndexSize () returns the index file size of this dataset

Db.linlin.totalSize () returns the total size of some datasets

Db.linlin.update (Query,object[,upsert_bool]) update a data set in this dataset

Db.linlin.validate () validates this data set

Db.linlin.getShardVersion () returns the data set share version number

Db.linlin.find ({' name ': ' Foobar '}) SELECT * from Linlin where name= ' Foobar '

Db.linlin.find () SELECT * FROM Linlin

Db.linlin.find ({' ID ': ten}). Count () Select COUNT (*) from Linlin where id=10

Db.linlin.find (). Skip (20) read 20 data from tenth of the query results select * FROM Linlin limit 10,20 ———-MySQL

Db.linlin.find ({' ID ': {$in: [25,35,45]}}) select * from Linlin where ID in (25,35,45)

Db.linlin.find (). Sort ({' ID ': -1}) SELECT * from Linlin ORDER BY ID Desc

Db.linlin.distinct (' name ', {' ID ': {$lt:}}) select DISTINCT (name) from Linlin where id<20

Db.linlin.group ({key:{' name ': ' true},cond:{' name ': ' foo '},reduce:function (obj,prev) {prev.msum+=obj.marks;}, INITIAL:{MSUM:0}})

Name,sum Select (marks) from Linlin GROUP by name

Db.linlin.find (' this.id<20′,{name:1}) select name from Linlin where id<20

Db.linlin.insert ({' name ': ' Foobar ', ' age ': +}) insert into Linlin (' name ', ' age ') VALUES (' Foobar ', 25)

Db.linlin.insert ({' name ': ' Foobar ', ' age ': +, ' email ': ' [email protected] '})

Db.linlin.remove ({}) Delete * from Linlin

Db.linlin.remove ({' Age ':}) Delete Linlin where age=20

Db.linlin.remove ({' age ': {$lt:}}) Delete Linlin where age<20

Db.linlin.remove ({' age ': {$lte:}}) Delete Linlin where age<=20

Db.linlin.remove ({' age ': {$gt:}}) Delete Linlin where age>20

Db.linlin.remove ({' age ': {$gte:}}) Delete Linlin where age>=20

Db.linlin.remove ({' age ': {$ne:}}) Delete Linlin where age!=20

Db.linlin.update ({' name ': ' Foobar '},{' $set ': {' age ': +}}) update Linlin set age=36 where name= ' Foobar '

Db.linlin.update ({' name ': ' Foobar '},{' $inc ': {' Age ': 3}}) update Linlin set age=age+3 where name= ' Foobar '

Python Learning database: MongoDB

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.