8.3 Operating the MongoDB database

  According to an authoritative survey, MongoDB database ranks second in the ten skills necessary for software developers in the era of big data, after HTML5. MongoDB is a document database based on distributed file storage. It can be said that it is one of the relational databases in the non-relational (Not Only SQL, NoSQL) database. It has the characteristics of strong and powerful query function, good support for big data processing, and aims to provide a scalable high-performance data storage solution for Web applications. MongoDB stores data as a document, and the data structure consists of key-value (key -> value) pairs. MongoDB documents are similar to JSON objects. Field values ​​can contain other documents, arrays, and arrays of documents.

  The MongoDB database can be downloaded from the official website, and the installation tutorial can be Baidu.

  The Python extension library pymongo perfectly supports the manipulation of MongoDB data and can be installed using the pip command. The following code demonstrates a part of the usage of pymongo to operate the MongoDB database.

1  import pymongo #Import                 module 2 
3  
client = pymongo.MongoClint( ' localhost ' ,27017)     #Connect to the database, 27017 is the default port 
4 db = client.students #Get                               database 5 db.collection_names()                              #View the list of data collection names 6 students = db.students #Get                             data set 7 students.find()
 8 9 for item in students.find():                       #Traverse data 10


  
 
     print (item)
 11      
12 wangwu={ ' name ' : ' Wangwu ' , ' age ' :20, ' sex ' : ' male ' }
 13 students.insert(wangwu) #Insert                            a record 
14  for item in students.find( { ' name ' : ' Wangwu ' }):     #Specify query condition 
15      print (item)
 16  
17students.find_one()                                #Get a record 
18 students.find_one({ ' name ' : ' Wangwu ' })
 19 students.find().count()                            #Get the total number of records 
20 students.remove({ ' name ' : ' Wangwu ' })                 #Delete a record 21 22 students.create_index(( ' name ' , pymongo.ASCENDING )) #Create   an index 23 24 students.update({ '
 

 
name ' : ' Zhangsan ' },{ ' $set ' :{ ' age ' :25}})    #Update database 
25  
26 students.remove()                                   #Clear database 
27  
28 Zhangsan = '' 
29 Lisi = '' 
30 Wangwu = '' 
31 students.insert_many([Zhangsan,Lisi,Wangwu] ) #Insert       multiple pieces of data 
32  
33  for item in students.find().sort( ' name ',pymongo.ASCENDING): #sort    the query results 
34      print (item)
 35     

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325093586&siteId=291194637