I have a db with documents with this format:
document1:
"source_dir":
[
"D:\dir1",
"D:\dir2"
]
document2:
"source_dir":
[
"D:\dir3",
"D:\dir4"
]
And in Python I have this path variable:
path = "D:\dir1\testFile.txt"
How can I query the db using the "path" variable so the return value is the document which "source_dir" array field contains an item that matches the start of path variable content?
In this case, the return value would be document1, since its source_dir field contains D:\dir1 and path starts with D:\dir1.
Thanks.
You can utilise aggregation operator $indexCP to search a string for an occurrence of a substring. The trick here is to reverse the search, using the source_dir value to search in the variable.
For example:
fullpath = "D:\\dir1\\testFile.txt"
pipeline = [
{"$unwind": "$source_dir"},
{"$match":{
"$expr":{
"$ne":[{"$indexOfCP":[fullpath, "$source_dir"]}, -1]
}}}]
result = client.dbname.collname.aggregate(pipeline)
for doc in result:
print(doc)
See also aggregation pipeline to find more operators