简体   繁体   中英

checking if a value exists in mongodb collection using pymongo

I have aa mongo db table in the following format

    [{"url":"www.example1.com", "name":"hans","age":30},
    {"url":"www.example2.com", "name":"x","age":34},
    {"url":"www.example3.com", "name":"y","age":35},
    {"url":"www.example4.com", "name":"z","age":36},
    {"url":"www.example5.com", "name":"b","age":37}]

I have two tables where i need to check for under two if conditions. I did in the following way

    val = "www.example1.com"
    if list(table1.find({"url": {"$eq": val}})):
        print("exist in table 1")
        if list(table2.find({"url": {"$eq": val}})):
            print("exist in table 2")
        else:
            print("not exist in table 2")
    else:
        print("not exist in table 1")

This gives me correct response but it seems to take more time in doing the check. Is there a better way to do this query using pymongo

With MongoDB v4.4+, you can use $unionWith . You may notice that there are two identical $match . This is for reducing intermediate table size to improve performance.

db.table1.aggregate([
  {
    $match: {
      "url": {
        "$eq": "www.example3.com"
      }
    }
  },
  {
    "$unionWith": {
      "coll": "table2",
      "pipeline": [
        {
          $match: {
            "url": {
              "$eq": "www.example3.com"
            }
          }
        }
      ]
    }
  }
])

Here is the Mongo playground for your reference.

I'd do it with findOne :

    val = "www.example1.com"
    if table1.find_one({"url": {"$eq": val}}):
        print("exist in table 1")
        if table2.find_one({"url": {"$eq": val}}):
            print("exist in table 2")
        else:
            print("not exist in table 2")
    else:
        print("not exist in table 1")

Which is much simpler than find() and fine_one() returns an element if found or None and not a cursor like find()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM