1. 程式人生 > 其它 >mongodb查詢報錯BSONElement: bad type問題

mongodb查詢報錯BSONElement: bad type問題

埃及客戶反饋資料無法導致,排查發現查詢Mongo報錯

org.bson.BsonSerializationException: Expected size to be 41, not 45.

因為沒有遇到過這個問題,所以記錄下;

遇見問題後,首先可以確定是資料錯誤導致的查詢報錯,猜測是bson序列化轉換的時候無法轉換導致的錯誤;於是思路為查詢到這條記錄然後修復;

首先思路為寫個簡單的指令碼來排查是哪條資料的問題:

#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
# Author: yxhe
# Date: 2022/3/8 09:53
# ----------------------------------------------------------

from bson import json_util
from pymongo import MongoClient

if __name__ == '__main__':
    client = MongoClient('mongodb://admin:[email protected]:27018/?authSource=admin')
    db = client['file']
    result = db["4B669F5FC553405BB9D90598DD83892D"].find({"batchId": "67C41509B080412AB2B741AAFBB38E77"},{'_id':1})
    for r in result:
        print(r)

執行發現報錯如下

pymongo.errors.OperationFailure: BSONElement: bad type 55, full error: {u'codeName': u'Location10320', u'code': 10320, u'ok': 0.0, u'errmsg': u'BSONElement: bad type 55'}

這時候已經可以確定無法通過查詢獲取到具體錯誤的資料資訊了,因為無法查詢;

於是準備修復下資料庫看是否可行;

通過mongo shell連線上db:

mongo --port 27017 -u "admin" -p "vmebAltj6TIUH7so" --authenticationDatabase "admin"

然後切換db:

use file

開始修復,修復官網有說明(https://docs.mongodb.com/v3.0/reference/method/db.repairDatabase/):

db.repairDatabase()

然後重新查詢,發現問題修復了;