我是 MongoDB 和 Pymongo 的新手,但從他們的 Mongo 大學學到了一些教訓。我有一個嵌套檔案,我只想從中提取特定值。我目前正在嘗試提取 PriceEGC 的數字部分,但沒有成功。我構建投影和提取特定值的代碼如下所示:
import os
import math
import pymongo
from pprint import pprint
from datetime import datetime
from bson.json_util import dumps
from bson.decimal128 import Decimal128
# more code above not shown
for collection in all_collections[:1]:
first_seen_date = collection.name.split("_")[-1]
projection = {
(more projections)...,
"RegoExpiryDate": "$Vehicle.Registration.Expiry",
"VIN": "$_id",
"ComplianceDate": None,
"PriceEGC": "$Price.FinalDisplayPrice", # <- this here is the problem
"Price": None,
"Reserve": "$Search.IsReservedDate",
"StartingBid": None,
"Odometer": "$Vehicle.Odometer",
(more projections)...
}
batch_size = 1
num_batches = math.ceil(collection.count_documents({}) / batch_size)
for num in range(1): # range(num_batches):
pipeline = [
{"$match": {}},
{"$project": projection},
{"$skip": batch_size * num},
{"$limit": batch_size},
]
aggregation = list(collection.aggregate(pipeline))
yield aggregation
if __name__ == "__main__":
print(dumps(next(get_all_collections()), indent=2))
典型的檔案如下所示:

我對聚合所做的是列印出這個單個檔案,先看看它是什么樣子,然后再將整個集合加載到某個地方。
我不想要的輸出是這樣的:
[{
(more key-value pairs)...,
"RegoExpiryDate": "2021-08-31T00:00:00.000Z",
"VIN": "JTMRBREVX0D087618",
"ComplianceDate": null,
"PriceEGC": {
"$numberDecimal": "36268.00" # <- Don't want this
},
"Price": null,
"Reserve": null,
"StartingBid": null,
"Odometer": 54567,
(more key-value pairs)...
}]
我想要的輸出是這樣的:
[{
(more key-value pairs)...,
"RegoExpiryDate": "2021-08-31T00:00:00.000Z",
"VIN": "JTMRBREVX0D087618",
"ComplianceDate": null,
"PriceEGC": 36268.00, (or) "PriceEGC": "36268.00", # <- Want this
"Price": null,
"Reserve": null,
"StartingBid": null,
"Odometer": 54567,
(more key-value pairs)...
}]
我將如何撰寫投影或管道,以便得到我想要的,如上所示?我試過了:
projection = {...,
"PriceEGC": "$Price.FinalDisplayPrice.$numberDecimal",
...
}
和
projection = {...,
"PriceEGC": {"$toDecimal": "$Price.FinalDisplayPrice"}
...
}
和
projection = {...,
"PriceEGC": Decimal128.to_decimal("$Price.FinalDisplayPrice")
...
}
并改變管道
pipeline = [
{"$match": {}},
{"$project": projection},
{"$toDecimal": "$Price.FinalDisplayPrice"},
{"$skip": batch_size * num},
{"$limit": batch_size},
]
uj5u.com熱心網友回復:
您所看到的是bson.json_util()MongoDB Decimal128 物件的表示。有關此資料型別的更多資訊,請參閱https://www.mongodb.com/developer/quickstart/bson-data-types-decimal128/
該bson.json_util()函式提供了$numberDecimal包裝器,以便在您希望稍后重新加載資料時保留資料型別。
如果您想要不同的行為,那么您可能需要使用常規json.dumps()并覆寫 Decimal128 行為,例如
from pymongo import MongoClient
from bson.decimal128 import Decimal128
import json
import bson
class CustomJsonEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, bson.decimal128.Decimal128):
return float(obj.to_decimal())
db = MongoClient()['mydatabase']
collection = db['mycollection']
collection.insert_one({'Price': {'FinalDisplayPrice': Decimal128('36268.00')}})
print(json.dumps(list(collection.find({}, {'_id': 0})), indent=4, cls=CustomJsonEncoder))
印刷:
[
{
"Price": {
"FinalDisplayPrice": 36268.0
}
}
]
uj5u.com熱心網友回復:
這里只是模式匹配,但是
"name": "$name.name.name",
似乎為
"RegoExpiryDate": "$Vehicle.Registration.Expiry",
所以嘗試相同的模式PriceEGC:
projection = {...
"PriceEGC": "$Price.FinalDisplayPrice.numberDecimal",
...}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/352441.html
上一篇:添加華為套件時出現“Couldnotfindcom.huawei.hms:location:6.0.0.302”錯誤
下一篇:多選ListView沒有回應
