Use the Python script to manipulate the MongoDB tutorial

  • 2020-05-09 18:51:27
  • OfStack

Connect to 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 inherits MongoClient. It is recommended to use MongoClient instead of Connection. (that is, MongoClient can be used and Connection can be used)


from pymongo import MongoClient
client = MongoClient('192.168.40.87', 27037)
db_name = 'TCL_Useraction'
db = client[db_name]
collection_useraction = db['useraction']

 

The database and collections are accessed by dictionary, and you can also access them by dot
Insert data

save() VS insert()

Both the save and insert functions can insert data into collection, but there are two differences:

1. The save function actually calls the insert or update functions according to the parameter conditions. If the object you want to insert does not exist, then they perform the same insertion operation.

2. insert can insert a list once without traversing, which is efficient; save needs to traverse the list and insert each one.

Update the data

For a single piece of data, you can update it using the save method

update(criteria, objNew, upsert, mult)
criteria: conditional expressions that need to be updated
objNew: updates the expression
upsert: insert a new document if the target record does not exist.
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 the data


db.users.drop() #  Delete the collection 

remove(self, spec_or_id=None, safe=None, multi=True, **kwargs)

# remove()  Used to delete a single or all document. The deleted document cannot be recovered. 
id = db.users.find_one({"name":"user2"})["_id"]
db.users.remove(id) #  According to the  id  delete 1 records 
db.users.remove() #  Deletes all records in the collection 
db.users.remove({'yy':5}) #  delete yy=5 The record of 

The query

  5. Query


  #  The query  age  Less than  15  the 
  for u in db.users.find({"age":{"$lt":15}}): print u

  5.1 queries a record


  #  The query  name  Is equal to the  user8  the 
  for u in db.users.find({"name":"user8"}): print u

  #  Get queried 1 a 
  u2 = db.users.find_one({"name":"user9"}) #  Return when not found  None
  print u2

  5.2 query for specific keys (fields)


  # select name, age from users where age = 21
  for u in db.users.find({"age":21}, ["name", "age"]): print u
  for u in db.users.find(fields = ["name", "age"]): print u

  5.3 sorting (SORT)


  pymongo.ASCENDING #  You can also use  1  To take the place of 
  pymongo.DESCENDING #  You can also use  -1  To take the place of 
  for u in db.users.find().sort([("age", pymongo.ASCENDING)]): print u  # select * from  A collection of  order by  key 1
  for u in db.users.find().sort([("age", pymongo.DESCENDING)]): print u # select * from  A collection of  order by  key 1 desc
  for u in db.users.find().sort([(" key 1", pymongo.ASCENDING), (" key 2", pymongo.DESCENDING)]): print u # select * from  A collection of  order by  key 1 asc,  key 2 desc
  for u in db.users.find(sort = [(" key 1", pymongo.ASCENDING), (" key 2", pymongo.DESCENDING)]): print u # sort  On the other 1 Kind of writing 
  for u in db.users.find({"name":"user9"}, sort=[['name',1],['sex',1]], fields = ["name", "age", 'sex']): print u #  Combination of writing 

  5.4 which line to read (SLICE) and how many lines to read (LIMIT)
       


# select * from  A collection of  skip 2 limit 3
  # MySQL  Writing:  select * from  A collection of  limit 2, 3
  for u in db.users.find().skip(2).limit(3): print u
  for u in db.users.find(skip = 2, limit = 3): print u

  #  You can use slices instead  skip & limit (mongo  In the  $slice  There seems to be a problem ) . 
  for u in db.users.find()[2:5]: print u

  #  A separate written 
  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

  5.5 multi-conditional queries (Conditional Operators)       # like can be queried using regular expressions
     


from pymongo import MongoClient
client = MongoClient('192.168.40.87', 27037)
db_name = 'TCL_Useraction'
db = client[db_name]
collection_useraction = db['useraction']

0

  5.6 IN
       


for u in db.users.find({"age":{"$in":(23, 26, 32)}}): print u  # select * from users where age in (23, 26, 32)
  for u in db.users.find({"age":{"$nin":(23, 26, 32)}}): print u # select * from users where age not in (23, 26, 32)

  5.7 total statistics (COUNT)
   


 print(db.users.count()) # select count(*) from users
  print(db.users.find({"age":{"$gt":30}}).count()) # select count(*) from users where age > 30

  5.8 OR
   


from pymongo import MongoClient
client = MongoClient('192.168.40.87', 27037)
db_name = 'TCL_Useraction'
db = client[db_name]
collection_useraction = db['useraction']

3

6. Does   exist (exists)


from pymongo import MongoClient
client = MongoClient('192.168.40.87', 27037)
db_name = 'TCL_Useraction'
db = client[db_name]
collection_useraction = db['useraction']

4

  7. Regular expression queries


from pymongo import MongoClient
client = MongoClient('192.168.40.87', 27037)
db_name = 'TCL_Useraction'
db = client[db_name]
collection_useraction = db['useraction']

5

  8. Element value matching for multilevel paths
      Document takes the hierarchical structure of JSON-like, so we can directly substitute the associated reference (Reference) for the traditional relational database by embedding (Embed).
      MongoDB supports namespace paths separated by "."; the multilevel paths in conditional expressions must be quoted

       


from pymongo import MongoClient
client = MongoClient('192.168.40.87', 27037)
db_name = 'TCL_Useraction'
db = client[db_name]
collection_useraction = db['useraction']

6

      {data:"abc"} simply matches whether the array attribute contains the element. $elemMatch handles more complex element lookup conditions. Of course, it can also be written as follows:
find({" data.a ":1, "data.b ":{'$gt':5}})

      can also directly use the sequence number to operate on the array:
      db. Collection name.find({"data.1":3}) # begins at 0


     


 #  As a collection of 1 Column content 
  {"classifyid":"test1",
     "keyword":[
        {"name":'test1', #  Change this value to  test5 ( Array index from 0 start , Subscripts are also used for points )
        "frequence":21,
        },
        {"name":'test2', #  The query for the subtable matches this value 
        "frequence":50,
        },
     ]
  }
  #  Modification of a subtable ( The rest of the child table remains the same )
  db. A collection of .update({"classifyid":"test1"}, {"$set":{"keyword.0.name":'test5'}})
  #  A query for a subtable 
  db. A collection of .find({"classifyid":"test1", "keyword.0.name":"test2"})


 
operation

  (1) $all: determines whether the array properties contain all the conditions.
     


 db.users.insert({'name':"user3", 'data':[1,2,3,4,5,6,7]})
  db.users.insert({'name':"user4", 'data':[1,2,3]})

  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       and $in. $in checks that the target attribute value is a member of the conditional expression, while $all requires that the attribute value contain all the conditional elements.

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


from pymongo import MongoClient
client = MongoClient('192.168.40.87', 27037)
db_name = 'TCL_Useraction'
db = client[db_name]
collection_useraction = db['useraction']

9

  (3) $type: determine the attribute type.
   


 for u in db.users.find({'t':{'$type':1}}): print u #  Query for numeric types 
  for u in db.users.find({'t':{'$type':2}}): print u #  Query for string type 

      type values:
              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: invert to return a document whose condition does not hold.
      seems to work only with regular and $mod 1??
Don't know how to use       # yet

  (5) $unset: as opposed to $set, removes the document property.
 


  for u in db.users.find({'name':"user1"}): print u
  #  Display, such as:  { "_id" : ObjectId("4c479885089df9b53474170a"), "name" : "user1", "age" : 15, "address" : [ "address1", "address2" ] }

  db.users.update({'name':"user1"}, {'$unset':{'address':1, 'age':1}})
  for u in db.users.find({'name':"user1"}): print u
  #  Display, such as:  { "_id" : ObjectId("4c479885089df9b53474170a"), "name" : "user1" }

  (6) $push: and $pushAll both add elements to the array attribute. It's like there's no difference between the two
   


 for u in db.users.find({'name':"user1"}): print u
  #  Display, such 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" : 15, "data" : [ 1 ], "name" : "user1" }

  db.users.update({'name':"user1"}, {'$pushAll':{'data':[2,3,4,5]}})
  for u in db.users.find({'name':"user1"}): print u
  #  Display, such as:  { "_id" : ObjectId("4c479885089df9b53474170a"), "age" : 15, "data" : [ 1, 2, 3, 4, 5 ], "name" : "user1" }

  (7) $addToSet: similar to $push, but added only if the element does not exist (Set means not repeating a collection of elements).
       


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.users.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': 12, u'_id': ObjectId('4c479896089df9b53474170b'), u'data': [1, 1, 2, 3, 4], u'name': u'user2'}
  #  It doesn't seem to automatically delete duplicates 

  (8) $each is used to 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.find({'name':"user2"}): print u
  #  Display:  {u'age': 12, 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 elements from the array attribute (by subscript), $pull by value, and $pullAll by all elements that match 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("4c47a133b48cde79c6780df0"), "data" : [ 1, 2, 3, 4, 5, 6, 7, 2, 3 ], "name" : "user2" }

  db.users.update({'name':"user2"}, {'$pop':{'data':1}}) #  Remove the last 1 An element 
  for u in db.users.find({'name':"user2"}): print u
  #  Display:  { "_id" : ObjectId("4c47a133b48cde79c6780df0"), "data" : [ 1, 2, 3, 4, 5, 6, 7, 2 ], "name" : "user2" }

  db.users.update({'name':"user2"}, {'$pop':{'data':-1}}) #  Remove the first 1 An element 
  for u in db.users.find({'name':"user2"}): print u
  #  Display:  { "_id" : ObjectId("4c47a133b48cde79c6780df0"), "data" : [ 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" }

  (10) $where: replace the somewhat ugly $lt, $gt code with JS.
      MongoDB has Javascript Engine (SpiderMonkey) built in. You can use JS Expression directly, or even use JS Function to write the more complex Code Block.

     


 db.users.remove() #  Deletes all records in the collection 
  for i in range(10):
    db.users.insert({'name':"user" + str(i), 'age':i})
  for u in db.users.find(): print u
  #  The display is as follows: 
  { "_id" : ObjectId("4c47b3372a9b2be866da226e"), "name" : "user0", "age" : 0 }
  { "_id" : ObjectId("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("4c47b3372a9b2be866da2275"), "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
  #  The display is 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
  #  The display is 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'}

  #  Use custom  function, javascript The grammatical 
  for u in db.users.find().where("function() { return this.age > 7 || this.age < 3;}"): print u
  #  The display is 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 articles: