You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python操作MongoDB从嵌套JSON数据中获取指定_id艺术家的对应价格

错误写法原因

  1. 你使用的aggregate仅做了文档级别的匹配,没有过滤artists数组内部的元素,所以会返回完整文档的全部艺术家信息
  2. 你使用的find写法误用了投影参数,find的第二个参数是投影规则,值只能为1(返回字段)或0(屏蔽字段),不能直接写数组元素的过滤条件,因此也会返回全部艺术家列表

正确实现方案

方案1:find + $elemMatch投影(最简实现)

直接在投影阶段用$elemMatch过滤数组,仅返回匹配的单个艺术家元素:

# 查询指定文档,仅返回artists数组中_id为1176704的元素
query_res = collection_name.find_one(
    {"_id": 9392991},
    {"artists": {"$elemMatch": {"_id": 1176704}}, "_id": 0}
)
# 提取目标价格
target_price = query_res["artists"][0]["price"]
print(target_price)

方案2:聚合管道实现(适合复杂场景)

如果后续有更复杂的统计、过滤需求,可以用聚合管道实现:

pipeline = [
    # 匹配目标文档
    {"$match": {"_id": 9392991, "artists._id": 1176704}},
    # 拆分artists数组为独立记录
    {"$unwind": "$artists"},
    # 过滤出_id匹配的艺术家
    {"$match": {"artists._id": 1176704}},
    # 仅返回价格字段,屏蔽冗余数据
    {"$project": {"_id": 0, "price": "$artists.price"}}
]
agg_res = list(collection_name.aggregate(pipeline))
target_price = agg_res[0]["price"]
print(target_price)

两种方案均会直接返回你需要的目标价格1779。


内容的提问来源于stack exchange,提问作者Nicolaj Spiegelhauer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 12:39:02