Python programming: drop-in replacement for TinyDB library MongoBD

TinyDB is a lightweight document database, similar in operation to MongoBD, and its storage method is Json

Documentation: https://tinydb.readthedocs.io/en/latest/index.html
github : https://github.com/msiemens/tinydb

code example

# -*- coding: utf-8 -*-

from tinydb import TinyDB, Query

db = TinyDB('db.json')

student = db.table("student")

# Insert data 
student . insert ( { "name" :  "Tom" ,  "age" :  23 } )

# 插入多条
student.insert_multiple([
    {"name": "Jack", "age": 24},
    {"name": "mary", "age": 25}
])


# Query all 
print ( student . all ( ) ) 
[ 
  { 'name' :  'Tom' ,  'age' :  23 } , 
  { 'name' :  'Jack' ,  'age' :  24 } , 
  { 'name' :  ' mary' ,  'age' :  25 } 
]

# query part 
query = Query ( ) 
result = student . search ( query . name ==  'Tom' ) 
print ( result ) 
# [{'name': 'Tom', 'age': 23}]

result = student.search(query.age > 24)
print(result)
# [{'name': 'mary', 'age': 25}]

# 逻辑查询
db.search(~ (User.name == 'John'))  # Negate
db.search((User.name == 'John') & (User.age <= 30))  # And
db.search((User.name == 'John') | (User.name == 'Bob'))  # Or

# 更新
student.update({'age': 26}, query.name == "Tom")
print(student.search(query.name=="Tom"))
# [{'name': 'Tom', 'age': 26}]

# 删除
student.remove(query.age < 25)
print(student.all())
# [{'name': 'Tom', 'age': 26}, {'name': 'mary', 'age': 25}]

# close 
db.close ( ) _

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54

Open db.json in the directory to view its storage format

{
    "_default":{

    },
    "student":{
        "1":{
            "name":"Tom",
            "age":26
        },
        "3":{
            "name":"mary",
            "age":25
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

Related: Python programming: drop-in replacement for TinyDB library MongoBD