0

I was expecting to run the function normally, being able to connect to the database, but it keeps returning Server selection errors, I've tried using both localhost and 172.17.0.2 (which is the docker inspect result), and it simply won't connect. The issue isn't the database as I can connect to it just fine through both localhost and 172.17.0.2.

I have added the MONGO_URL env var to the local.settings.json, and it is being grabbed since it says it failed to connect to the right IP

env = os.getenv("MONGO_URL")
client = pymongo.MongoClient(env)
db = client["data"]
col = db["objects"]

Also, weirdly enough, I've tried to print stuff before the client invocation when I was trying to debug it, and the connection would run before the print statements, even though they were placed before the connection

[2023-05-31T16:04:33.213Z] Executed 'Functions.HttpTrigger1' (Failed, Duration=30422ms)
[2023-05-31T16:04:33.213Z] System.Private.CoreLib: Exception while executing function: Functions.HttpTrigger1. System.Private.CoreLib: Result: Failure
[2023-05-31T16:04:33.213Z] Exception: ServerSelectionTimeoutError: 172.17.0.2:27017: timed out, Timeout: 30s, Topology Description: <TopologyDescription topology_type: Unknown, servers: [<ServerDescription ('172.17.0.2', 27017) server_type: Unknown, rtt: None, error=NetworkTimeout('172.17.0.2:27017: timed out')>]>

I think it's fine, but just in case, here's my local.settings.json

{
  "IsEncrypted": false,
  "Values": {
    "FUNCTIONS_WORKER_RUNTIME": "python",
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "AzureWebJobsFeatureFlags": "EnableWorkerIndexing",
    "MONGO_URL": "mongodb://172.17.0.2:27017"
  }
}
Podpah
  • 1

1 Answers1

0

I have referred link MSDOC Azure Cosmos DB for MongoDB and Azure function

Code:

connection_string = os.environ["MongoConnectionString"]
try:

client = MongoClient(connection_string)

db = client['your_database_name']

collection = db['your_collection_name']

documents = collection.find()

for  document  in  documents:
logging.info(document)

return  func.HttpResponse("Data retrieved successfully.")

except  pymongo.errors.PyMongoError as  e:

logging.error('Error connecting to Azure Cosmos DB: %s',  str(e))

return  func.HttpResponse("Error connecting to Azure Cosmos DB.",  status_code=500)

enter image description here

Output:

enter image description here

enter image description here

enter image description here

Sampath
  • 810
  • 2
  • 2
  • 13
  • I believe I am connecting through the connection string? It's a mongodb:// and not a https://. I simply named the environment variable Mongo URL but I do believe I am using the connection string – Podpah Jun 06 '23 at 12:41
  • Hello @Podpah try my code – Sampath Jun 06 '23 at 13:03
  • I'll give it a try but it seems like we have the same things ```python env = os.getenv("MONGO_URL") client = pymongo.MongoClient(env) db = client["data"] col = db["objects"] ``` ```python connection_string = os.environ["MongoConnectionString"] client = MongoClient(connection_string) db = client['your_database_name'] collection = db['your_collection_name'] ``` os.getenv is a wrapper for os.environ.get https://stackoverflow.com/a/16924553/21999308 We are both using MongoClient to connect, and we are choosing database/collection in the same way – Podpah Jun 06 '23 at 14:59
  • I have just tried your code, I am still getting the server selection error – Podpah Jun 06 '23 at 15:06
  • other method ```def main(req: func.HttpRequest) -> func.HttpResponse: logging.info('Python HTTP trigger function processed a request.') # Obtain the connection string for your Azure Cosmos DB account connection_string = 'connection string' try: # Create a MongoClient object and pass in the connection string client = MongoClient(connection_string) # Access a specific database within your Cosmos DB account db = client['sampath'] ``` – Sampath Jun 06 '23 at 16:14
  • ```documents = collection.find() for document in documents: logging.info(document) return func.HttpResponse("Data retrieved successfully.") except pymongo.errors.PyMongoError as e: logging.error('Error connecting to Azure Cosmos DB: %s', str(e)) return func.HttpResponse("Error connecting to Azure Cosmos DB.", status_code=500) ``` – Sampath Jun 06 '23 at 16:17
  • Console [Output](https://i.imgur.com/WZ3khc9.png) URL [Output](https://i.imgur.com/H7QtOiG.png) for time out Troubleshoot refer [this](https://learn.microsoft.com/en-us/azure/azure-functions/recover-python-functions?tabs=vscode%2Cbash&pivots=python-mode-configuration) – Sampath Jun 06 '23 at 16:37
  • even by removing the environment variable, it won't connect. Same server selection error – Podpah Jun 08 '23 at 10:08
  • The issue I'm facing is not featured in there, so that reference doesn't really help – Podpah Jun 09 '23 at 08:18
  • will search relevant links for time out issues and get back to you – Sampath Jun 09 '23 at 08:27
  • Troubleshoot [time](https://github.com/MicrosoftDocs/azure-docs/blob/main/articles/data-factory/connector-troubleshoot-mongodb.md) Out [reference](https://www.mongodb.com/community/forums/t/mongodb-timeout-error/216297/3) [link](https://www.mongodb.com/community/forums/t/connect-timeout-and-execution-timeout-in-nodejs-driver/2129) – Sampath Jun 13 '23 at 05:13