Is it possible to use materialized path trees with python?

Hi, I need help with this section of the MongoDB docs

Im using python and it seems like this part of the docs lack a python translation. Is it even possible to use this feature with python?

If i for example save nodes like this: [{ "_id": "Programming", "path": ",Books," }, { "_id": "Databases", "path": ",Books,Programming," }]

and then query the data like this: db.categories.find( { path: "^,Books," } )
I dont get any output. Maybe it’s not even thought to implement this with python. What can I do?

edit: note, that I changed the statements to work with python. I put quotation marks around the “_id” and the “path” statements, as well as around the statement in the “find” function.

I am pretty sure you need to use

I am not absolutely sure since I do not use the python driver.

1 Like

Hi @Moritz_Honscheidt

@steevej suggestion is correct, you should use the $regex operator in Python passing everything as a dictionary for it’s options. This will allow you to perform the necessary regular expression searching that is discussed in the manual page you’ve referenced.

If you have more specific Python questions, I’d ask them in the Drivers & ODM category as there will be more readers there who have greater familiarity with using regular expressions and Python.

Kindest regards,

1 Like

Thank you Eoin, would you as well show me what the code would look like with my example above?

Hi @Moritz_Honscheidt
In terms of:

It would look like the code extract below. I’ve excluded error handling, any connection details beyond assuming a default local mongod.

   from pymongo import MongoClient
   client = MongoClient()
   db = client.test
   categories_col = db.categories
   categories_col.insert_one({"subjects":[{ "_id": "Programming", "path": ",Books," }, { "_id": "Databases", "path": ",Books,Programming," }]})
   query = { "subjects.path": { "$regex": '^,Books,' } }

This code segment should be sufficient to give an indicative step on where to go next. In terms of follow-ups, I’d suggest you post further questions to Working with Data or to ODM & Drivers as this has moved outside of the scope of M220P and there will be a wider pool of viewers in those forums who can provide further assistance should you require it.

Kindest regards,

1 Like