Home > database >  How to search for a value in two different type of field or index or heading of mongodb using python
How to search for a value in two different type of field or index or heading of mongodb using python

Time:12-20

I am new to any kind of programming. This is an issue I encountered when using mongodb. Below is the collection structure of the document I imported from two different csv files.

{
    "_id": {
        "$oid": "61bc4217ed94f9d5fe6a350c"
    },
    "Telephone Number": "8429950810",
    "Date of Birth": "01/01/1945"
}

{
    "_id": {
        "$oid": "61bc4217ed94f9d5fe6a350c"
    },
    "Telephone Number": "8129437810",
    "Date of Birth": "01/01/1998"
}

{
    "_id": {
        "$oid": "61bd98d36cc90a9109ab253c"
    },
    "TELEPHONE_NUMBER": "9767022829",
    "DATE_OF_BIRTH": "16-Jun-98"
}

{
    "_id": {
        "$oid": "61bd98d36cc9090109ab253c"
    },
    "TELEPHONE_NUMBER": "9567085829",
    "DATE_OF_BIRTH": "16-Jan-91"
}

The first two entries are from a csv and the next two entries from another csv file. Now I am creating a user interface where users can search for a telephone number. How to write the query to search the telephone number value in both the index ( Telephone Number and TELEPHONE_NUMBER) using find() in the above case. If not possible is there a way to change the index's to a desired format while importing csv to db. Or is there a way where I create two different collection and then import csv to each collections and then perform a collective search of both the collections. I am using pymongo for all the operations.

Thankyou.

CodePudding user response:

Assuming you have your connection string to connect via pymongo. Then the following is an example of how to query for the telephone number "8429950810":

from pymongo import MongoClient
client = MongoClient("connection_string")
db = client["db"]
collection = db["collection"]
results = collection.find({"Telephone Number":"8429950810"})

Please note this will return as type cursor, if you would like your documents in a list consider wrapping the query in list() like so:

results = list(collection.find({"Telephone Number":"8429950810"}))

CodePudding user response:

You can use or query if different key is used to store same type of data.

yourmongocoll.find({"$or":[ {"Telephone Number":"8429950810"}, {"TELEPHONE_NUMBER":8429950810}]})
  • Related