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

MongoDB如何查询数组中的指定元素?

MongoDB 查询实现方案

文档结构

存储的MongoDB文档如下:

{
    "_id" : ObjectId("54fa059ce4b01b3e086c83e9"),
    "field1" : "value1",
    "field2" : "value2",
    "field3" : [ 
        {
            "abc123": ["somevalue", "somevalue"]
        },
        {
            "xyz345": ["somevalue", "somevalue"]
        }
    ]
}

需求说明

传入目标键名(比如abc123),需要返回以下两种格式之一:

  1. 包含目标键的对象:
{
     "abc123": ["somevalue", "somevalue"]
}
  1. 直接返回键对应的数组值:
["somevalue", "somevalue"]

实现代码(PyMongo)

方案1:返回包含目标键的对象

用聚合查询拆分数组、匹配目标键后重构结果:

from pymongo import MongoClient

client = MongoClient()
db = client.your_database_name
collection = db.your_collection_name

target_key = "abc123"

pipeline = [
    {"$unwind": "$field3"},  # 拆分数组field3
    {"$match": {f"field3.{target_key}": {"$exists": True}}},  # 匹配含目标键的数组元素
    {"$replaceRoot": {"newRoot": "$field3"}}  # 将匹配到的元素作为根文档返回
]

result = list(collection.aggregate(pipeline))[0]  # 取第一个匹配结果
print(result)

方案2:直接返回数组值

在聚合查询基础上提取目标值,或用find_one简化实现:

聚合方式

from pymongo import MongoClient

client = MongoClient()
db = client.your_database_name
collection = db.your_collection_name

target_key = "abc123"

pipeline = [
    {"$unwind": "$field3"},
    {"$match": {f"field3.{target_key}": {"$exists": True}}},
    {"$project": {"value": f"$field3.{target_key}", "_id": 0}}  # 仅提取目标值
]

result = list(collection.aggregate(pipeline))[0]["value"]
print(result)

简化find_one方式

from pymongo import MongoClient

client = MongoClient()
db = client.your_database_name
collection = db.your_collection_name

target_key = "abc123"

document = collection.find_one({f"field3.{target_key}": {"$exists": True}}, {f"field3.$": 1})
if document:
    result = document["field3"][0][target_key]
    print(result)

内容的提问来源于stack exchange,提问作者Navjot Gwal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 04:45:57