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

如何使用CouchDB Mango API筛选数组中匹配指定条件的元素?

问题:CouchDB Mango API筛选数组元素时返回完整数组,如何只保留匹配项?

我用Go语言访问CouchDB,想通过Mango API筛选数组中包含指定值的元素,使用$elemMatch操作符后,返回的文档仍包含完整的数组,而非仅匹配的元素。

文档示例

{
  "id": "id1",
  "user_info": [
    {
      "name": "kk",
      "age": "17"
    },
    {
      "name": "jj",
      "age": "21"
    },
    {
      "name": "kk",
      "age": "19"
    }
  ]
}

当前查询语句

{
  "selector": {
    "id": "id1",
    "user_info": {
      "$elemMatch": {
        "name": "kk"
      }
    }
  }
}

问题说明

当前返回结果包含完整的user_info数组,但我需要仅保留name为"kk"的数组元素。


解决方案

$elemMatch的作用是筛选出包含匹配数组元素的文档,而非过滤数组本身的元素。要实现数组元素过滤,需结合fields参数和$filter操作符。

正确的Mango查询

{
  "selector": {
    "id": "id1",
    "user_info": {
      "$elemMatch": {
        "name": "kk"
      }
    }
  },
  "fields": [
    "id",
    {
      "user_info": {
        "$filter": {
          "input": "user_info",
          "as": "item",
          "cond": {"$eq": ["$$item.name", "kk"]}
        }
      }
    }
  ]
}

关键说明

  1. selector部分保留$elemMatch,确保只返回包含目标元素的文档;
  2. fields中通过$filter遍历user_info数组,将每个元素命名为item,仅保留name等于"kk"的项。

Go语言代码示例

package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	// 构造Mango查询
	query := map[string]interface{}{
		"selector": map[string]interface{}{
			"id": "id1",
			"user_info": map[string]interface{}{
				"$elemMatch": map[string]string{"name": "kk"},
			},
		},
		"fields": []interface{}{
			"id",
			map[string]interface{}{
				"user_info": map[string]interface{}{
					"$filter": map[string]interface{}{
						"input": "user_info",
						"as":    "item",
						"cond":  map[string][]interface{}{"$eq": []interface{}{"$$item.name", "kk"}},
					},
				},
			},
		},
	}

	// 序列化为JSON格式,用于发送CouchDB请求
	jsonData, err := json.MarshalIndent(query, "", "  ")
	if err != nil {
		fmt.Println("JSON序列化错误:", err)
		return
	}
	fmt.Println(string(jsonData))
}

执行该查询后,返回的文档中user_info数组将仅包含name为"kk"的元素,符合预期结果。


内容的提问来源于stack exchange,提问作者K JH

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 16:45:52