MongoDB::如何按文档中的字段计数文档?



我在这个网站和我在网上找到的其他教程的帮助下慢慢地用python学习MongoDB。我需要人帮忙汇总和统计我的文件。

解释一下:在我的MongoDB实例中,我已经有1000个文档,每个文档跟踪我的(虚构的)租赁公司提供的汽车。所有的汽车文档都有这样的格式:

{
"model": "Honda Civic",
"license_plate": "ABC-1234",
"attributes":
{
"rented": "YES",
...lots more data here...
}
}

我已经学会了足够的MongoDB/python构建简单的管道来搜索数据。这是一个搜索所有文件的管道,它可以找出汽车的型号、牌照和"已租"字样。状态:

mydatabase = client.CARS_DB
mycollection = mydatabase.RENTAL_LOT_A
listOfRules = mycollection.distinct("model")
for rule in listOfRules:
match_variable = {
"$match": { 'model': rule }
}
project_variable = {
"$project": {
'_id': 0,
'model': 1,
'license_plate': 1,
'attributes.rented': 1
}
}
pipeline = [
match_variable,
project_variable
]
results = mycollection.aggregate(pipeline)
for r in results:
print(r)
print("- - - - - - - - - - - - - - - - -")

输出为:

{'model': 'Honda Civic', 'license_plate': 'ABC-1234', 'attributes': {'rented': 'YES'}}
- - - - - - - - - - - - - - - - -
{'model': 'Toyota Camry', 'license_plate': 'ABC-5678', 'attributes': {'rented': 'YES'}}
- - - - - - - - - - - - - - - - -
{'model': 'Honda Civic', 'license_plate': 'DEF-1001',  'attributes': {'rented': 'no'}}
- - - - - - - - - - - - - - - - -

到目前为止,一切顺利。

但让我烦恼的是:如果我想让所有的汽车单独列出,上面的方法很好。但如果我想看到更大的、综合的图片。我不关心车牌因为我想看到的是这样的:

MODEL              TOTAL
========================
Honda Civic         134
Toyota Camry        432
Ford Mustang         93
Honda Accord        738
Chevorlet Corvette    3

…其中"total"中的值;列是文档的数量,其中"model"相当于"本田思域";等等......更好的做法是:

MODEL                       TOTAL
=================================
Honda Civic, rented            76
Honda Civic, available         58
Toyota Camry, rented          245
Toyota Camry, available       187
Ford Mustang, rented           60
Ford Mustang, available        33
Honda Accord, rented          137
Honda Accord, available       601
Chevorlet Corvette, rented      3
Chevorlet Corvette, available   0

现在我在"模型"上进行聚合。和"attributes.rented".

我真的不关心sql表格式,我只是希望能够从MongoDB中提取这些数据。肯定有办法修改我的管道,或者从零开始创造新的东西。我试过python字典、db.collection.countDocuments()和这个网站上的一些其他帖子;没有运气。有谁能建议一个方法吗?谢谢你。

完全披露::我也问过同样的问题

您将需要使用$group来创建这样的聚合,组_id是您放置想要通过它们聚合的字段的地方。$project步骤是按照需要格式化数据:

db.collection.aggregate([
{
$group: {
_id: {model: "$model", rented: "$attributes.rented"},
count: {$sum: 1}
}
},
{
$project: {
model: "$_id.model",
stauts: {
$cond: [{$eq: ["$_id.rented", "YES"]}, "rented", "available"]},
count: 1,
_id: 0
}
}
])

看看它在操场的例子中是如何工作的

  • 我建议在属性下使用status字段,它可以包含几个状态选项(例如,'租用'/'可用'/'onRepair'),而不是rented"布尔">

最新更新