3

I have to query my MongoDB database on fields' type.
This is a document of my collection user: enter image description here

In MongoDB there is a table for the available BSON types and their corresponding numbers. For example:

1 -> Double
2 -> String
3 -> Object
4 -> Array
......
......
......

$type selects the documents where the value of the field is an instance of the specified numeric BSON type:

 { field: { $type: <BSON type> } }

So, for example with this query:

db.user.find({ street: { $type: 2 }})

I get all documents containing a street field that is a string.

Ather this introduction in nutshell suppose I want to know which is the type of street field.
In this case I have to query my database until I get some documents:

db.user.find({ street: { $type: 1 }})
db.user.find({ street: { $type: 2 }})
db.user.find({ street: { $type: 3 }})
db.user.find({ street: { $type: 4 }})
.......
.......
.......

So I have to query my database a lot of times with the same query changing the type number.
Are there other possibilities to know which is the type of a field beyond the previous?

Community
  • 1
  • 1
harry-potter
  • 1,981
  • 5
  • 29
  • 55
  • this may help:http://stackoverflow.com/questions/6336973/how-do-i-describe-a-collection-in-mongo – Dev Dec 22 '15 at 19:11

2 Answers2

0

you can try this tool variety - a Schema Analyzer for MongoDB.

Say your data:

db.users.insert({name: "Tom", bio: "A nice guy.", pets: ["monkey", "fish"], someWeirdLegacyKey: "I like Ike!"});
db.users.insert({name: "Dick", bio: "I swordfight.", birthday: new Date("1974/03/14")});
db.users.insert({name: "Harry", pets: "egret", birthday: new Date("1984/03/14")});
db.users.insert({name: "Geneviève", bio: "Ça va?"});
db.users.insert({name: "Jim", someBinData: new BinData(2,"1234")});

use :

$ mongo test --eval "var collection = 'users'" variety.js

Output:

+------------------------------------------------------------------+
| key                | types              | occurrences | percents |
| ------------------ | ------------       | ----------- | -------- |
| _id                | ObjectId           |           5 |    100.0 |
| name               | String             |           5 |    100.0 |
| bio                | String             |           3 |     60.0 |
| birthday           | String             |           2 |     40.0 |
| pets               | Array(4),String(1) |           5 |     40.0 |
| someBinData        | BinData-old        |           1 |     20.0 |
| someWeirdLegacyKey | String             |           1 |     20.0 |
+------------------------------------------------------------------+
Dev
  • 13,492
  • 19
  • 81
  • 174
0

this will group by field type.

db.collection.aggregate(
    [
        {
            $group : 
            {
                _id : 
                    {  "$type": "$yourkey"  }, 
                num : {$sum : 1}
            }
        }
    ])
Will Chia
  • 1
  • 1