MONGO Database Basic Operations

Source: Internet
Author: User
Tags mongoclient

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 Import  = mongoclient ('192.168.40.87', 27037'tcl_useraction  '== db['useraction']

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

2. 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.

3. Updating 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)
4. Delete data
Db.users.drop ()#Delete Collection#Remove (self, spec_or_id=none, Safe=none, Multi=true, **kwargs)#Remove () deletes a single document or all documents, and the deleted document cannot be recovered. id = db.users.find_one ({"name":"User2"})["_id"]db.users.remove (ID)#Delete a record by IDDb.users.remove ()#Delete all records in the collectionDb.users.remove ({'yy': 5})#Delete a yy=5 record

5. Enquiry
# query for age less than 15  for  in Db.users.find ({' age': {"$lt":}}):     Print(u)

5.1 Querying a record
#query name equals User8. forUinchDb.users.find ({"name":"User8"}):    Print(U)#gets the query for aU2 = Db.users.find_one ({"name":"User9"})#return None when not found    Print(U2)

5.2 Query specific key (fields)

Special Note :
In the 3.0 version, this parameter has been renamed projection , if used fields will be an error

#select name, age from the users where age = forUinchDb.users.find ({" Age": 21}, ["name"," Age"]):    Print(U) forUinchDb.users.find (Fields = ["name"," Age"]):    Print(u)

5.3 Sorting (sort)
Pymongo. Ascending#You can also replace it with aPymongo. Descending#You can also use-to replace forUinchDb.users.find (). sort ([(" Age", Pymongo. Ascending)]):Print(u)#SELECT * FROM collection name ORDER by key 1 forUinchDb.users.find (). sort ([(" Age", Pymongo. Descending)]):Print(u)#SELECT * FROM collection name ORDER by key 1 desc forUinchDb.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 forUinchDb.users.find (sort = [("Key 1", Pymongo. Ascending), ("Key 2", Pymongo. Descending)]):Print(u)#another way to sort forUinchDb.users.find ({"name":"User9"}, sort=[['name', 1],['Sex', 1]], fields = ["name"," Age",'Sex']):    Print(u)#Combination notation



Small examples of scenarios used in FOF projects:
ImportPymongoImportdatetime fromPymongoImportmongoclientconnection= Mongoclient ('localhost') DB=Connection.fofstock_cache=Db.stock_cache#post = {"20160301": "Mike", "text": "My First blog post!", "tags": ["MongoDB", "Python", "Pymongo"], "date": Datetime.da Tetime.utcnow ()}Post = {'Date':'20160302',"stocks":['001','002'],'EP':{'001':' -','002':'101'},'Market_value':{'001':'100m','002':'101m'},'Stock_share':{'001':'100s','002':'101s'}}#Db.stock_cache.drop ()#Db.stock_cache.insert (POST)Docs = Db.stock_cache.find ({'Date':'20160301'}) forDocinchDocs:stocks= Doc.get ('stocks')    Print('stocks', Stocks) forStockinchStocks:market_value= Doc.get ('Market_value'). Get (stock)Print('Market_value', Market_value) Market_value= Doc.get ('Stock_share'). Get (stock)Print('Stock_share', Market_value)#Mongocall.insert ({' name ': ' Li '})



MONGO Database Basic Operations

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.