tutorial on using the Python script to manipulate MongoDB

Source: Internet
Author: User
Tags mongoclient
Connecting to a database

Mongoclient VS Connection

Class Mongoclient (Pymongo.common.BaseObject) | Connection to MongoDB. | | Method Resolution Order: |   mongoclient |   Pymongo.common.BaseObject |   __builtin__.object |class Connection (pymongo.mongo_client. Mongoclient) | Connection to MongoDB. | | Method Resolution Order: |   Connection |   Pymongo.mongo_client. mongoclient |   Pymongo.common.BaseObject |   __builtin__.object


From the inheritance of these two classes, connection is inherited by Mongoclient, and it is recommended to use mongoclient instead of connection. (That is, mongoclient can use the method connection can be used)

From Pymongo Import mongoclientclient = mongoclient (' 192.168.40.87 ', 27037) db_name = ' tcl_useraction ' db = Client[db_name ]collection_useraction = db[' useraction ']

The database and collection are accessed through a dictionary, and you can access it by using the. (dot) method.
Inserting data

Save () VS insert ()

Both the Save and insert functions of MONGODB can insert data into collection, but there are two differences between the two:

The Save function actually calls the INSERT or update function according to the parameter condition. If the data object that you want to insert exists, the Insert function will error, and the Save function changes the original object, or if the object you want to insert does not exist, Then they perform the same insert operation. Here you can use a few words to summarize the difference between them, that is, the so-called "rectify any mistakes, nothing in addition."

Insert can be inserted into a list at a time, without traversing, high efficiency, save will need to traverse the list, insert.

Update data

For individual data, you can use the Save method after updating

Update (criteria, objnew, Upsert, mult)
Criteria: conditional expression that needs to be updated
Objnew: Updating an expression
Upsert: If the target record does not exist, insert a new document.
Multi: Whether to update multiple documents.

Collection_useraction.update ({' gid ': last_gid, ' time ': L_date}, {' $set ': {' gid ': last_gid}, ' $set ': {' time ': L_date}, ' $ Addtoset ': {' categories ': Category_data}}, Upsert=true)


Delete data

Db.users.drop () # Remove the collection remove (self, spec_or_id=none, Safe=none, Multi=true, **kwargs) # Remove () to delete a single or all documents, the deleted document cannot be recovered. id = db.users.find_one ({"Name": "User2"}) ["_id"]db.users.remove (ID) # Delete a record based on ID db.users.remove () # Delete all records in the collection db.users.remove ({' yy ': 5}) # Delete yy=5 Records

Inquire

5. Enquiry

  # Query for you in Db.users.find of age less than 15  ({"Age": {"$lt":}}): Print U

5.1 Querying a record

  # query name equals user8 for  u in Db.users.find ({"Name": "User8"}): Print U

  # get a  U2 = Db.users.find_one ({"Name": "User9"}) # returns none when not found  print U2

5.2 Query specific key (fields)

  # select name, age from the users where age = +  for u in Db.users.find ({"Age": +}, ["Name", "Age"]): Print u for  u in Db.users.find (fields = ["Name", "Age"]): Print U

5.3 Sorting (sort)

  Pymongo. Ascending # can also be used as a substitute for  Pymongo. Descending # can also be used-to replace  the for U in Db.users.find (). Sort ([("Age", Pymongo. Ascending)]): Print u  # select * FROM collection name ORDER by key 1  for u in Db.users.find (). Sort ([("Age", Pymongo. Descending)]): Print u # select * FROM collection name ORDER by key 1 desc for  u in Db.users.find (). Sort ([("Key 1", Pymongo. Ascending), ("Key 2", Pymongo. Descending)]): Print u # select * FROM collection name ORDER by key 1 ASC, key 2 desc for  u in db.users.find (sort = [("Key 1", Pymongo. Ascending), ("Key 2", Pymongo. Descending)]: Another way to print U # sort is for  u in Db.users.find ({"Name": "User9"}, sort=[[' name ', 1],[' sex ', 1]], and fields = [ "Name", "Age", ' sex '): print U # combination notation

5.4 read from the first line (SLICE), read how many lines (LIMIT)

# SELECT * FROM collection name Skip 2 limit 3  # MySQL notation: SELECT * from collection name limit 2, 3 for  u in Db.users.find (). Skip (2). Limi T (3): Print u  for u in db.users.find (skip = 2, limit = 3): Print u  # can be sliced instead of skip & limit (the $slice in MONGO seems to have Problem).  for u in Db.users.find () [2:5]: Print u  # separate write for  u in Db.users.find (). Skip (2): Print u for  u in db.users . Find (Skip=1): Print u for  u in Db.users.find (). Limit (5): Print U for  u in db.users.find (limit = 3): Print U

More than 5.5 pieces of query (Conditional Operators) # like can use regular expression query

# SELECT * from users where name = ' User3 ' and "Age >" and "Age <"  for U "db.users.find ({' age ': {' $gt ': 12, ' $lt ': +}, ' name ': ' User3 '}): Print u  # SELECT * from users where name = ' User1 ' and "age = + for  u in DB.USERS.F IND ({"Age": +, "name": "User1"}): Print U

5.6 In

For u in Db.users.find ({' age ': {"$in":(()}): Print u  # SELECT * from the users where age in (at  U in Db.users.find ({' age ': {"$nin":(()}): Print u # SELECT * from the users where age not in (23, 26, 32)

5.7 Total Statistics (count)

Print (Db.users.count ()) # Select COUNT (*) from the Users  print ({"Age": {"$GT": +}}). Count ()) # Select Count (*) from the users where age > 30

5.8 OR

For you in Db.users.find ({"$or": [{"Age": +}, {"Age":-}]}): Print u # select * FROM collection name where key 1 = value 1 or key 1 = value 2 for  u i N Db.users.find ({"$or": [{"Age": {"$lte": +}}, {"Age": {"$gte": []}): Print u # select * FROM collection name where key 1 <= value 1 or key 1 & gt;= Value 2

6. Presence (exists)

  Db.users.find ({' sex ': {' $exists ': True}}) # select * from collection name where exists key 1  db.users.find ({' sex ': {' $exists ': False} }) # SELECT * from collection name where NOT EXISTS key 1

7. Regular expression queries

  

8. Multi-level Path element value matching
Document takes json-like this hierarchy, so we can use embedding (Embed) directly instead of the associated reference (Reference) of the traditional relational database.
MongoDB supports namespace paths that are split with ".", and the multi-level path in the conditional expression must be quoted

# If the key contains an array, simply match whether the array property contains the element to query out the DB. The collection name. Find_one ({' Address ': ' Address1 '}) # address is a group of numbers, which is only required to contain a # query result such as: {"_id":  ObjectId ("4c479885089df9b53474170a"), "name": "User1", "Address": ["Address1", "Address2"]} # The multi-level path in the conditional expression must be in quotation marks, separated by "." U = db. The collection name. Find_one ({"IM.QQ": 12345678}) # Query results such as: {"_id": ObjectId ("4c479885089df9b53474170a"), "name": "user1", "im":  {"MSN": "User1@hotmail.com", "QQ": 12345678}} Print u[' im ' [' MSN '] #显示: user1@hotmail.com # Update DB for multi-stage path. Collection name. Update ({"IM.QQ": 12345678}, {' $set ': {"im.qq": 12345}) # Query Package For u in db.users.find with a specific key ({"Im.qq": {' $exists ': True}}, {"Im.qq": 1}): The Print U # is displayed as: {"_id": ObjectId ("4c479885089df9 b53474170a ")," im ": {" QQ ": 12345}} for u in Db.users.find ({' Data ':" ABC "}): Print U # Display as: {" _id ": ObjectId (" 4c47a 481b48cde79c6780df5 ")," name ":" User8 "," data ": [{" A ": 1," B ": Ten}, 3," abc "]} for U in Db.users.find ({' data ': {') $elemMatch ': {' A ': 1, ' B ': {' $gt ': 5}}} ': Print U # displayed as: {"_id": ObjectId ("4c47a481b48cde79c6780df5 ")," name ":" User8 "," data ": [{" A ": 1," B ": Ten}, 3," abc "]} 

{data: ' abc '} simply matches whether the array property contains the element. $elemMatch can handle more complex element lookup criteria. Of course, it can be written as follows:
Db. Collection name. Find ({"DATA.A": 1, "data.b": {' $gt ': 5}})

An array can also be manipulated directly using the ordinal:
Db. Collection name. Find ({"Data.1": 3}) # Sequence number starting from 0


# such as a list of contents of the collection  {"Classifyid": "Test1",     "keyword": [        {"name": ' Test1 ', # will modify this value to Test5 (array subscript starting from 0, subscript is also used point)        " Frequence ": +,        },        {" name ": ' Test2 ', # Child table of the query, will match to this value        " frequence ": [     ]},"  }  # child table modification ( The other contents of the child table do not change)  db. Collection name. Update ({"Classifyid": "Test1"}, {"$set": {"keyword.0.name": ' Test5 '}})  # query  for child tables Db. Collection name. Find ({"Classifyid": "Test1", "Keyword.0.name": "Test2"})



Operation

(1) $all: Determines whether the array property contains all conditions.

Db.users.insert ({' name ': ' User3 ', ' Data ': [1,2,3,4,5,6,7]})  Db.users.insert ({' name ': ' User4 ', ' data ': [+]}) For  u in Db.users.find ({' data ': {' $all ': [2,3,4]}}): Print u  # display: {"_id": ObjectId ("4c47a133b48cde79c6780df0") , "name": "User3", "Data": [1, 2, 3, 4, 5, 6, 7]}

Note the difference between the $in. $in is to check that the target property value is a member of a conditional expression, and $all requires that the property value contain all the conditional elements.

(2) $size: Matches the number of array attribute elements.

For u in Db.users.find ({' data ': {' $size ': 3}}): Print u  # shows only the number of matches for this array: {"_id": ObjectId ("4c47a13bb48cde79c6780df1"), "Name": "User4", "Data": [1, 2, 3]}

(3) $type: Determines the property type.

For u in Db.users.find ({' t ': {' $type ': 1}}): Print u # query for the numeric type for  u in Db.users.find ({' t ': {' $type ': 2}}): Print u # query character String type of

Type value:
Double:1
String:2
Object:3
Array:4
Binary Data:5
Object Id:7
Boolean:8
Date:9
Null:10
Regular expression:11
JavaScript code:13
Symbol:14
JavaScript code with SCOPE:15
32-bit integer:16
Timestamp:17
64-bit integer:18
Min key:255
Max key:127

(4) $not: Reverse, indicating that the return condition of the document is not valid.
Seems to be only used with the regular and $mod together????
# still don't know how to use

(5) $unset: In contrast to $set, the removal of document properties.

  For u in Db.users.find ({' name ': ' User1 '}): Print u  # displayed as: {"_id": ObjectId ("4c479885089df9b53474170a"), "name": "Use R1 "," Age ":" Address ": [" Address1 "," Address2 "]}  db.users.update ({' name ': ' User1 '}, {' $unset ': {' address ': 1, ' A GE ': 1}}) for  u in Db.users.find ({' name ': ' User1 '}): Print u  # Display as: {"_id": ObjectId ("4c479885089df9b53474170a") , "name": "User1"}

(6) $push: and $ pushall All add elements to an array property. # It seems like there's no difference #

For u in Db.users.find ({' name ': ' User1 '}): Print u  # displayed as: {"_id": ObjectId ("4c479885089df9b53474170a"), "age": 15, " Name ":" User1 "}  db.users.update ({' Name ':" User1 "}, {' $push ': {' data ': 1}}) for  u in Db.users.find ({' Name ':" User1 "}): Print u  # display such as: {" _id ": ObjectId (" 4c479885089df9b53474170a ")," Age ": [1]," name ":" User1 " }  db.users.update ({' name ': ' User1 '}, {' $pushAll ': {' data ': [2,3,4,5]}}) for  u in Db.users.find ({' Name ': "User1 "}): Print u  # displayed as: {" _id ": ObjectId (" 4c479885089df9b53474170a ")," Age ": [1, 2, 3, 4, 5]," name ":" User1 "}

(7) $addToSet: Similar to $push, but added only if the element does not exist (set means that the collection of elements is not duplicated).

Db.users.update ({' name ': ' User2 '}, {' $unset ': {' data ': 1}})  db.users.update ({' name ': ' User2 '}, {' $addToSet ': {') Data ': 1}})  db.users.update ({' name ': ' User2 '}, {' $addToSet ': {' data ': 1}}) for  u in Db.users.find ({' Name ': " User2 "}): Print u  # display: {" _id ": ObjectId (" 4c479896089df9b53474170b ")," Data ": [1]," name ":" User2 "}  Db.user S.update ({' name ': ' User2 '}, {' $push ': {' data ': 1}}) for  u in Db.users.find ({' name ': ' User2 '}): Print u  # display: {"_id ": ObjectId (" 4c479896089df9b53474170b ")," Data ": [1, 1]," name ":" User2 "}  to add multiple elements, use $each.  db.users.update ({' name ': ' User2 '}, {' $addToSet ': {' data ': {' $each ': [1,2,3,4]}}}) for  u in Db.users.find ({' Name ': "User2"}): Print u  # display: {u ' age ':--U ' _id ': ObjectId (' 4c479896089df9b53474170b '), U ' data ': [1, 1, 2, 3, 4], u ' Name ': U ' user2 '}  # seemingly does not automatically delete duplicates

(8) $each add multiple elements.

  Db.users.update ({' name ': ' User2 '}, {' $unset ': {' data ': 1}}) db.users.update ({' name ': ' User2 '}, {' $addToSet ': {' data ': 1  }}) for u in Db.users.find ({' name ': ' User2 '}): Print U # display: {"_id": ObjectId ("4c479896089df9b53474170b"), "Data": [1 ], "name": "User2"} db.users.update ({' name ': ' User2 '}, {' $addToSet ': {' data ': {' $each ': [1,2,3,4]}}}) for u in DB.USERS.F IND ({' name ': ' User2 '}): Print U # display: {u ' age ': $, U ' _id ': ObjectId (' 4c479896089df9b53474170b '), U ' data ': [1, 2, 3, 4], U ' Name ': U ' user2 '} db.users.update ({' name ': ' User2 '}, {' $addToSet ': {' data ': [1,2,3,4]}}) for u in Db.users.find ({' Name ': "  User2 "}): Print U # display: {" _id ": ObjectId (" 4c479896089df9b53474170b ")," Data ": [1, 2, 3, 4, [1, 2, 3, 4]]," name ": "User2"} db.users.update ({' name ': ' User2 '}, {' $unset ': {' data ': 1}}) db.users.update ({' name ': ' User2 '}, {' $addToSet ': { ' Data ': [1,2,3,4]}}) for u in Db.users.find ({' name ': ' User2 '}): Print U # display: {"_id": ObjectId ("4c47a133b48cde79c6780df0 ")," Data ": [[1, 2, 3, 4]]," name " : "User2"} 

(9) $pop: Removes the element of an array attribute (removed by subscript), $pull removes by value, $pullAll removes all elements that conform to the commit.

Db.users.update ({' name ': ' User2 '}, {' $unset ': {' data ': 1}}) db.users.update ({' name ': ' User2 '}, {' $addToSet ': {' data ': { ' $each ': [1, 2, 3, 4, 5, 6, 7, 2, 3]}}) for u in Db.users.find ({' name ': ' User2 '}): Print U # display: {"_id": ObjectId ("4c4 7a133b48cde79c6780df0 ")," Data ": [1, 2, 3, 4, 5, 6, 7, 2, 3]," name ":" User2 "} db.users.update ({' name ':" User2 "}, {' $ Pop ': {' data ': 1}} # removes the last element for u in Db.users.find ({' name ': ' User2 '}): Print U # display: {"_id": ObjectId ("4c47a133b48cde7 9c6780df0 ")," Data ": [1, 2, 3, 4, 5, 6, 7, 2]," name ":" User2 "} db.users.update ({' name ': ' User2 '}, {' $pop ': {' data ':-1 }}) # Remove the first element for u in Db.users.find ({' name ': ' User2 '}): Print U # display: {"_id": ObjectId ("4c47a133b48cde79c6780df0"), "D ATA ": [2, 3, 4, 5, 6, 7, 2]," name ":" User2 "} db.users.update ({' name ': ' User2 '}, {' $pull ': {' Data ': 2}}) # Remove all 2 for U in Db.users.find ({' name ': ' User2 '}): Print U # display: {"_id": ObjectId ("4c47a133b48cde79c6780df0"), "Data": [3, 4, 5, 6 , 7], "name": "User2"} db.usErs.update ({' name ': ' User2 '}, {' $pullAll ': {' data ': [3,5,6]}}) # Remove 3,5,6 for u in Db.users.find ({' name ': ' User2 '}): Print U # display: {"_id": ObjectId ("4c47a133b48cde79c6780df0"), "Data": [4, 7], "name": "User2"}

$where: Use JS code instead of some ugly $lt, $gt.
MongoDB has built-in Javascript Engine (SpiderMonkey). You can use JS Expression directly, and even use JS Function to write more complex Code Block.

 Db.users.remove () # Delete all records in the collection for I in range: Db.users.insert ({' Name ': ' User ' + str (i), ' age ': i}) for u in db.us Ers.find (): Print U # is displayed as follows: {"_id": ObjectId ("4c47b3372a9b2be866da226e"), "name": "User0", "Age": 0} {"_id": OBJ  Ectid ("4c47b3372a9b2be866da226f"), "name": "User1", "Age": 1} {"_id": ObjectId ("4c47b3372a9b2be866da2270"), "name": "User2", "Age": 2} {"_id": ObjectId ("4c47b3372a9b2be866da2271"), "name": "User3", "Age": 3} {"_id": ObjectId (" 4c47b3372a9b2be866da2272 ")," name ":" User4 "," Age ": 4} {" _id ": ObjectId (" 4c47b3372a9b2be866da2273 ")," name ":" User5 "," Age ": 5} {" _id ": ObjectId (" 4c47b3372a9b2be866da2274 ")," name ":" User6 "," Age ": 6} {" _id ": ObjectId (" 4c47b33 72a9b2be866da2275 ")," name ":" User7 "," Age ": 7} {" _id ": ObjectId (" 4c47b3372a9b2be866da2276 ")," name ":" User8 "," age ": 8} {" _id ": ObjectId (" 4c47b3372a9b2be866da2277 ")," name ":" User9 "," Age ": 9} for u in Db.users.find ({" $where ":" This.age > 7 | | This.Age < 3 "}): Print U # appears as follows: {u ' age ': 0.0, U ' _id ': ObjectId (' 4c47b3372a9b2be866da226e '), U ' name ': U ' User0 '} {u ' age ': 1.0, U ' _id ': ObjectId (' 4c47b3372a9b2be866da226f '), U ' name ': U ' user1 '} {u ' age ': 2.0, U ' _id ': ObjectId (' 4c47b3372a9b2be866da2270 '), U ' name ': U ' user2 ' {u ' age ': 8.0, U ' _id ': ObjectId (' 4c47b3372a9b2be866da2276 '), U ' name ': U ' User8 ' {u ' age ': 9.0, U ' _id ': ObjectId (' 4c47b3372a9b2be866da2277 '), U ' name ': U ' user9 '} for U in Db.users.find (). where ( "This.age > 7 | | This.age < 3 "): Print U # is shown as follows: {u ' age ': 0.0, U ' _id ': ObjectId (' 4c47b3372a9b2be866da226e '), U ' name ': U ' User0 '} {u ' AG E ': 1.0, U ' _id ': ObjectId (' 4c47b3372a9b2be866da226f '), U ' name ': U ' user1 '} {u ' age ': 2.0, U ' _id ': ObjectId (' 4c47b3372a9b2be866da2270 '), U ' name ': U ' user2 ' {u ' age ': 8.0, U ' _id ': ObjectId (' 4c47b3372a9b2be866da2276 '), U ' name ': U ' User8 ' {u ' age ': 9.0, U ' _id ': ObjectId (' 4c47b3372a9b2be866da2277 '), U ' name ': U ' user9 '} # using Custom function, JavaScript syntax For u in Db.users.find (). where ("function () {return this.age > 7 | | This.age < 3;} "): Print U # appears as follows: {u ' age ': 0.0, U ' _id ': ObjectId (' 4c47b3372a9b2be866da226e '), U ' name ': U ' User0 '} {u ' Age ': 1.0, U ' _id ': ObjectId (' 4c47b3372a9b2be866da226f '), U ' name ': U ' user1 '} {u ' age ': 2.0, U ' _id ': ObjectId (' 4c47b3372a9b2be866da2270 '), U ' name ': U ' user2 ' {u ' age ': 8.0, U ' _id ': ObjectId (' 4c47b3372a9b2be866da2276 '), U ' name ': U ' User8 ' {u ' age ': 9.0, U ' _id ': ObjectId (' 4c47b3372a9b2be866da2277 '), U ' name ': U ' user9 '}
  • 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.