The MondoDB Query Function allows the creation of a function to perform an MLDB SQL query against a MongoDB collection. It is similar to the SQL Query function.
A new function of type mongodb.query
named <id>
can be created as follows:
mldb.put("/v1/functions/"+<id>, {
"type": "mongodb.query",
"params": {
"uriConnectionScheme": <string>,
"collection": <string>,
"output": <SqlQueryOutput>
}
})
with the following key-value definitions for params
:
Field, Type, Default | Description |
---|---|
uriConnectionScheme | MongoDB connection scheme. mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database]] |
collection | The collection to query. |
output | Controls how the query output is converted into a row. |
For this example, we will use a MongoDB database populated with data provided by the book MongoDB In Action. The zipped json file is available at http://mng.bz/dOpd.
Here we create the query function on the MongoDB zips database zips collection.
mldb.put("/v1/functions/mongo_query", {
"type": "mongodb.query",
"params": {
"connectionScheme": 'mongodb://somehost.mldb.ai:11712/zips',
"collection": 'zips'
}
})
A direct call to the function looks like
import json
mldb.get('/v1/functions/mongo_query/application',
input={'query' : json.dumps({'zip' : {'$eq' : '60623'}})}
).json()
With the output
{
'output': {
'_id': u'57d2f5eb21af5ee9c4e22302',
'city': 'CHICAGO',
'loc': [['x', [87.7157, '2016-09-09T17:48:27Z']],
['y', [41.849015, '2016-09-09T17:48:27Z']]],
'pop': 112047,
'state': 'IL',
'zip': '60623'
}
}
Here is an example of the function beign used within a query.
mldb.query("""
SELECT mongo_query({query: '{"loc.x" : {"$eq" : 73.968312}}'}) AS *
""")
_id | city | loc.x | loc.y | pop | state | zip |
---|---|---|---|---|---|---|
_rowName | ||||||
result | 57d2f5eb21af5ee9c4e24e4f | NEWORK | 73.968312 | 40.797466 | 100027 | NY |