Python MongoDB查询用法示例详细介绍

2021年4月10日11:50:40 发表评论 1,162 次浏览

MongoDB 是一个跨平台的面向文档的非关系(即NoSQL)数据库程序。它是一个开放源代码文档数据库, 以键值对的形式存储数据。

什么是MongoDB查询?

MongoDB查询用于通过查询运算符指定选择过滤器, 同时通过以下方式从集合中检索数据db.find()方法。我们可以使用查询对象轻松过滤文档。要将过滤器应用于集合, 我们可以将指定所需文档条件的查询作为参数传递给此方法, 该参数是该方法的可选参数db.find()方法。

查询选择器:

以下是MongoDB查询中使用的一些运算符的列表。

操作 语法 描述
相等 {"key" : "value"} 匹配等于指定值的值。
小于 {"key" :{$lt:"value"}} 匹配小于指定值的值。
大于 {"key" :{$gt:"value"}} 匹配大于指定值的值。
小于等于 {"key" :{$lte:"value"}} 匹配小于或等于指定值的值。
大于等于 {"key" :{$lte:"value"}} 匹配大于或等于指定值的值。
不等于 {"key":{$ne: "value"}} 匹配所有不等于指定值的值。
逻辑与 { "$and":[{exp1}, {exp2}, …, {expN}] } 用逻辑AND连接查询子句, 返回与两个子句的条件都匹配的所有文档。
逻辑或 { "$or":[{exp1}, { 用逻辑OR将查询子句连接起来, 将返回匹配任一子句条件的所有文档。
逻辑非 { "$not":[{exp1}, {exp2}, …, {expN}] } 反转查询表达式的效果, 并返回与查询表达式不匹配的文档。

我们在其上运行的数据库或集合:

Python MongoDB查询用法示例详细介绍1

示例1:

# importing Mongoclient from pymongo
from pymongo import MongoClient 
  
  
# Making Connection
myclient = MongoClient( "mongodb://localhost:27017/" ) 
   
# database 
db = myclient[ "mydatabase" ]
   
# Created or Switched to collection
# names: lsbin
Collection = db[ "lsbin" ]
  
# Filtering the Quantities greater
# than 40 using query.
cursor = Collection.find({ "Quantity" :{ "$gt" : 40 }})
  
# Printing the filterd data.
print ( "The data having Quantity greater than 40 is:" )
for record in cursor: 
     print (record) 
      
# Filtering the Quantities less 
# than 40 using query.
cursor = Collection.find({ "Quantity" :{ "$lt" : 40 }})
  
# Printing the filterd data.
print ( "\nThe data having Quantity less than 40 is:" )
for record in cursor: 
     print (record)

输出如下:

Python MongoDB查询用法示例详细介绍2

示例2:

# importing Mongoclient from pymongo
from pymongo import MongoClient 
  
  
# Making Connection
myclient = MongoClient( "mongodb://localhost:27017/" ) 
   
# database 
db = myclient[ "mydatabase" ]
   
# Created or Switched to collection 
# names: lsbin
Collection = db[ "lsbin" ]
  
# Filtering the (Quantities greater than
# 40 AND greater than 40) using AND query.
cursor = Collection.find({ "$and" :[{ "Quantity" :{ "$gt" : 40 }}, { "Quantity" :{ "$gt" : 50 }}]})
  
# Printing the filterd data.
print ("Quantities greater than 40 AND\
Quantities greater than 40 :")
for record in cursor: 
     print (record) 
  
# Filtering the (Quantities greater than
# 40 OR greater than 40) using OR query.
cursor = Collection.find({ "$or" :[{ "Quantity" :{ "$gt" : 40 }}, { "Quantity" :{ "$gt" : 50 }}]})
  
# Printing the filterd data.
print ()
print ("Quantities greater than 40 OR\
Quantities greater than 40 :")
for record in cursor: 
     print (record)

输出如下:

Python MongoDB查询用法示例详细介绍3

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: