简体   繁体   中英

Querying mongoDB using pymongo (completely new to mongo/pymongo)

If this question seems too trivial then please let me know in the comments, I will do further research on how to solve it.

I have a collection called products where I store details of a particular product from different retailers. The schema of a document looks like this -

{
    "_id": "uuid of a product",
    "created_at": "timestamp",
    "offers": [{
            "retailer_id": 123,
            "product_url": "url - of -a - product.com",
            "price": "1"
        },
        {
            "retailer_id": 456,
            "product_url": "url - of -a - product.com",
            "price": "1"
        }
    ]
}

_id of a product is system generated. Consider a product like 'iPhone X'. This will be a single document with URLs and prices from multiple retailers like Amazon, eBay, etc.

Now if a new URL comes into the system, I need to make a query if this URL already exists in our database. The obvious way to do this is to iterate every offer of every product document and see if the product_url field matches with the input URL. That would require loading up all the documents into the memory and iterate through the offers of every product one by one. Now my question arises -

Is there a simpler method to achieve this? Using pymongo? Or my database schema needs to be changed since this basic check_if_product_url_exists() is too complex?

MongoDB provides searching within arrays using dot notation .

So your query would be:

db.collection.find({'offers.product_url': 'url - of -a - product.com'})

The same syntax works in MongoDB shell or pymongo.

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