简体   繁体   English

使用 pymongo 查询 mongoDB(对 mongo/pymongo 来说是全新的)

[英]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.我有一个名为 products 的集合,我在其中存储来自不同零售商的特定产品的详细信息。 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.产品的 _id 是系统生成的。 Consider a product like 'iPhone X'.考虑像“iPhone X”这样的产品。 This will be a single document with URLs and prices from multiple retailers like Amazon, eBay, etc.这将是一个包含来自多个零售商(如 Amazon、eBay 等)的 URL 和价格的单个文档。

Now if a new URL comes into the system, I need to make a query if this URL already exists in our database.现在如果一个新的 URL 进入系统,我需要查询这个 URL 是否已经存在于我们的数据库中。 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.执行此操作的显而易见的方法是迭代每个产品文档的每个报价,并查看 product_url 字段是否与输入 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?使用pymongo? Or my database schema needs to be changed since this basic check_if_product_url_exists() is too complex?或者我的数据库架构需要更改,因为这个基本的 check_if_product_url_exists() 太复杂了?

MongoDB provides searching within arrays using dot notation . MongoDB 提供使用点符号在数组内搜索。

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.相同的语法适用于 MongoDB shell 或 pymongo。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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