【问题标题】:How to query a item inside of an object in a array In Mongodb如何在MongoDB中查询数组中对象内的项目
【发布时间】:2020-05-18 20:13:30
【问题描述】:

您好,不知道如何正确提出这个问题,但我的问题是我正在学习构建一个以 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"
    }
  ]
}

【问题讨论】:

  • 那是购物车收藏吗?所以你只需要检查一个产品是否已经存在于products数组中,你不需要用户文档/购物车吗?
  • 它是集合中的一个文档,感谢@bigbounty 感谢我使用 $elemMatch 找到的文档链接,它有效

标签: python arrays mongodb pymongo cart


【解决方案1】:

您可以查询:

db.getCollection('collection_name').find({'products.product_id':{ $exists: true }})

此查询将返回具有product_id 字段的记录。

【讨论】:

    【解决方案2】:

    根据您描述的用例 - 当您想要进行更新时,除了 product_id 之外,您确实有 customer_id。

    因此,要确定产品是否存在于客户的购物车中,您可以在查询中同时包含客户 ID 和 product_id。

    db.getCollection(<collection_name>).findOne({'customer_id': <customer_id>, 'products.product_id':<product_id>})
    

    如果此产品 ID 存在于客户的购物车中,则查询将返回它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-22
      • 2018-07-23
      • 1970-01-01
      相关资源
      最近更新 更多