Determine length of NumberLong in Python
<p>I have some documents in my MongoDB collection, some of which contain NumberLong values :</p>

<pre><code>{ "_id" : ObjectId("57e4d18df4733211b613f199"), "parentid" : "P1000016", "phone" : NumberLong("9819733299") }
{ "_id" : ObjectId("57e4d18df4733211b613f19a"), "parentid" : "P1000014", "phone" : "24306574|9920599404||9920840077|865" }
{ "_id" : ObjectId("57e4d18df4733211b613f19b"), "parentid" : "P1000017", "phone" : "25821154|25821188|" }
</code></pre>

<p>I'm importing them into my python code and extracting each number using split (if I have multiple number sets in phone) or otherwise, directly appending to a list.</p>

<p>But I want only those numbers in my list whose length is greater than 6. </p>

<p>So I tried using this:</p>

<pre><code>#Initializing MongoDB client
client = MongoClient()

#Connection
db = client.mumbai
collection = db.mumbaiLive

for post in collection.find():
    shops.append(post) 

for shop in shops:
    phones = shop["phone"].split("|")
    for eachPhone in phones:
        if (len(eachPhone) &lt; 6):
            pass
</code></pre>

<p>It works fine until it encounters a NumberLong value. 
When I perform  </p>

<p><code>print "len = ", len(eachPhone)</code>, I get </p>

<pre><code>len =
</code></pre>

<p>I even tried converting it into string first but got the same result.</p>

<p>What I want : I want to skip 'pass'ing the NumberLong values using length check or any other method (like determining whether a value is NumberLong or not).</p>

<p>Depending on your use case, you can either add a filter to your query, to only return field <code>phone</code> where the value is string by utilising <a href="https://docs.mongodb.com/manual/reference/operator/query/type/#type" rel="nofollow">$type</a></p>



<pre><code>client = MongoClient()
db = client.database
collection = db.collection

for document in collection.find({"phone":{"$type":"string"}}):
    print document
</code></pre>

<p>Which would 'skip' passing <code>phone</code> containing <code>NumberLong</code> value to your function. </p>

<p>Alternatively, if you would like to process <code>phone</code> with <code>NumberLong</code> value in a different manner you can utilise Python <a href="https://docs.python.org/2/library/functions.html#isinstance" rel="nofollow">isinstance</a>. See below for an example: </p>



<pre><code>for doc in collection.find():
    if isinstance(doc["phones"], long):
        print("Number of digits: %s" % len(str(doc["phones"])))
    else:
        print("Number is not NumberLong")
</code></pre>

<p>If you are using Python 2, you have to detect <code>long</code>. If you are using Python 3, you can just detect <code>int</code> . </p>

python mongodb pymongo