[英]pymongo/mongodb: query if an element in an array of mongodb object
[英]How to query a item inside of an object in a array In Mongodb
您好,不知道如何正確提出這個問題,但我的問題是我正在學習使用 mongoddb 作為數據庫構建購物車。 當用戶將產品添加到他們的購物車時,我想查看他們是否已經在購物車中擁有該商品。 如何查詢數據庫以查看數據庫中是否存在 product_id。 這是我的購物車數據庫模式,如果我能獲得示例代碼,我也在使用 python 和 pymongo。
{
"_id": "5ec2df02e10dce76aa83b8b7",
"cart_session": "test",
"customer_id": 101,
"cart_total": 20,
"cart_items": 3,
"products": [
{
"product_id": 1,
"product_name": "Yellow T-Shirt",
"price": 10,
"quantity": 3,
"image": "imageurl"
},
{
"product_id": 2,
"product_name": "Red Braclet",
"price": 5,
"quantity": 1,
"image": "imageurl"
},
{
"product_id": 3,
"product_name": "Blue Braclet",
"price": 5,
"quantity": 1,
"image": "imageurl"
}
]
}
您可以查詢:
db.getCollection('collection_name').find({'products.product_id':{ $exists: true }})
此查詢將返回具有product_id
字段的記錄。
根據您描述的用例 - 當您想要進行更新時,除了 product_id 之外,您確實有 customer_id 。
因此,要確定產品是否存在於客戶的購物車中,您可以在查詢中同時包含客戶 ID 和 product_id。
db.getCollection(<collection_name>).findOne({'customer_id': <customer_id>, 'products.product_id':<product_id>})
如果此產品 ID 存在於客戶的購物車中,則查詢將返回它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.