【问题标题】:Get a specific value from JSON data using MongoDB python使用 MongoDB python 从 JSON 数据中获取特定值
【发布时间】:2022-01-09 20:38:29
【问题描述】:

我正在尝试从嵌套的 JSON 对象中获取特定值。我尝试了以下方法,但在所有情况下,我都从所有嵌套对象中获取了所有特定值。 在这种情况下,我想从一位艺术家那里获得具体价格,id 为:1176704。

collection_name = dbname["Tattooparlor"]

cus_details = collection_name.aggregate([{"$match": {"artists._id": 1176704}}])
print(cus_details)

for r in cus_details:
   print(r)

for r in collection_name.find({"_id": 9392991}, {"artists._id": 1176704}):
   print(r)
   for x in r["artists"]:
       print(x["price"])

在所有情况下,它都会返回 1779、2730、4530 或完整的对象,而我只希望它返回 1779。

我的 JSON 对象如下所示

【问题讨论】:

  • 试试$elemMatch 投影。
  • @prasad_ 我在尝试 $elemMatch "$elemMatch is not allowed in this atlas tier" 时收到此错误
  • 这可能意味着您的 Atlas Cluster 层(例如 M0 等)具有一些有限的功能。您可以查找有关 限制 的 Atlas 文档。也许这可能有效:$ (projection).

标签: python json database mongodb


【解决方案1】:

你试过了吗?你必须找到艺术家的身份证,然后打印出他/她的价格。

for result in collection_name.find({"_id": 9392991}):
    for arr in r["artists"]:
       if arr["_id"] == 1176704:
          print(arr["price"])

【讨论】:

  • 我在 r["artists"]["_id"] 中收到 field_value 这个错误:TypeError: list indices must be integers or slices, not str
  • 查看我的编辑。没有意识到艺术家是一个字典数组。
【解决方案2】:

如果您尝试仅限制价格字段 collection_name.find({"_id": 9392991}, {"artists._id": 1176704},{price:1})

【讨论】:

    猜你喜欢
    • 2021-06-22
    • 2019-03-30
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    • 2021-04-21
    • 2016-03-10
    • 1970-01-01
    相关资源
    最近更新 更多