Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

363
Views
Python bson library : get bson alias

I am looking for a type_of method as below :

import bson
bson.type_of(42)  # it should return "int".
bson.type_of("hello")  # it should return "string".
type("hello").__name__   # it returns "str" and not "string" therefore no suitable.

The results I want ( int and string) are the BSON alias (see https://docs.mongodb.com/manual/reference/bson-types/).

Does this method type_of already exist ?

It is okay if it returns the types' numbers ( 1 for Double, 2 for String ...).

Thank you,

Edit : Here is the solution I have for the moment:

type_of = {
    type(2.5).__name__: "number",
    type(1).__name__: "number",
    type("a_string").__name__: "string",
    type([1, 2]).__name__: "array",
    type(True).__name__: "bool"
}  # type_of[type(3).__name__] returns "number"
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

If you want the actual BSON types (number is not a bson type) I'm not sure there is a way. I've used this function to help sort out what python will encode the object as:

def what_bson_type(input):
    import bson
    return bson._ELEMENT_GETTER[bson.BSON.encode({"t":input})[4]].__name__[5:]

Note: these "types" do not match the bson spec, but they have been good enough to help me in the past.

>>> what_bson_type("hi")
'string'
>>> what_bson_type(1)
'int'
>>> what_bson_type(sys.maxint)
'int64'
>>> what_bson_type(True)
'boolean'
>>> what_bson_type({"a":"b"})
'object'
>>> what_bson_type(1.2)
'float'
>>> what_bson_type([1,2])
'array'
>>> what_bson_type(re.compile(r".*"))
'regex'
>>> what_bson_type(bson.Binary("hi"))
'binary'
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!