📜  Python MongoDB – 不同()

📅  最后修改于: 2022-05-13 01:55:43.878000             🧑  作者: Mango

Python MongoDB – 不同()

MongoDB 是一个跨平台、面向文档的数据库,它基于集合和文档的概念。它以键值对的形式存储数据,是一个 NoSQL 数据库程序。 NoSQL 一词的意思是非关系型的。有关该主题的深入介绍,请参阅 MongoDB 和Python 。现在让我们了解一下 PyMongo 中distinct()函数的使用。

清楚的()

PyMongo 包含distinct()函数,该函数在单个集合中查找并返回指定字段的不同值,并在数组中返回结果。

让我们创建一个示例集合:

# importing the module
from pymongo import MongoClient
   
# creating a MongoClient object 
client = MongoClient() 
     
# connecting with the portnumber and host 
client = MongoClient("mongodb://localhost:27017/") 
   
# accessing the database 
database = client['database'] 
    
# access collection of the database 
mycollection = mydatabase['myTable'] 
  
documents = [{"_id": 1, "dept": "A",
                  "item": {"code": "012", "color": "red"},
                  "sizes": ["S", "L"]},
             {"_id": 2, "dept": "A",
                  "item": {"code": "012", "color": "blue"},
                  "sizes": ["M", "S"]},
             {"_id": 3, "dept": "B",
                  "item": {"code": "101", "color": "blue"},
                  "sizes": "L"},
             {"_id": 4, "dept": "A",
                  "item": {"code": "679", "color": "black"},
                  "sizes": ["M"]}]
  
mycollection.insert_many(documents)
for doc in mycollection.find({}):
    print(doc)

输出 :

{'_id': 1, 'dept': 'A', 'item': {'code': '012', 'color': 'red'}, 'sizes': ['S', 'L']}
{'_id': 2, 'dept': 'A', 'item': {'code': '012', 'color': 'blue'}, 'sizes': ['M', 'S']}
{'_id': 3, 'dept': 'B', 'item': {'code': '101', 'color': 'blue'}, 'sizes': 'L'}
{'_id': 4, 'dept': 'A', 'item': {'code': '679', 'color': 'black'}, 'sizes': ['M']}

现在我们将;使用distinct()方法:

  • 返回字段的不同值
  • 返回嵌入字段的不同值
  • 返回数组字段的不同值
  • 返回特定查询
# distinct() function returns the distinct values for the
# field dept from all documents in the mycollection collection
print(mycollection.distinct('dept'))
  
# distinct values for the field color, 
# embedded in the field item, from all documents
# in the mycollection collection
print(mycollection.distinct('item.color'))
  
# returns the distinct values for the field sizes 
# from all documents in the mycollection collection
print(mycollection.distinct("sizes"))
  
# distinct values for the field code, 
# embedded in the field item, from the documents 
# in mycollection collection whose dept is equal to B.
print(mycollection.distinct("item.code", {"dept" : "B"}))

Output :

['A', 'B']
['red', 'blue', 'black']
['L', 'S', 'M']
['101']