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

MongoDB嵌套数组贷款数据的查询、删除、更新技术问询

MongoDB 嵌套数组操作解决方案

问题1:筛选出category为"rural"的贷款数据

你的loans字段是二维嵌套数组,以下两种实用方案满足不同需求:

方案1:保留原文档结构,仅过滤符合条件的贷款

db.collection("collection_name").aggregate([
  // 匹配目标日期的文档
  {$match: {br_date: this.data.date}},
  // 展开外层loans数组
  {$unwind: "$loans"},
  // 过滤每个外层数组中category为rural的贷款
  {$addFields: {
    "loans": {$filter: {
      input: "$loans",
      cond: {$eq: ["$$this.category", "rural"]}
    }}
  }},
  // 过滤掉空的loans数组(可选)
  {$match: {"loans.0": {$exists: true}}},
  // 重新组合外层数组,恢复原结构(可选)
  {$group: {
    _id: "$_id",
    brdate: {$first: "$brdate"},
    brName: {$first: "$brName"},
    email: {$first: "$email"},
    loans: {$push: "$loans"}
  }}
]).toArray()

方案2:直接提取所有符合条件的独立贷款条目

如果不需要保留原文档结构,仅需贷款数据:

db.collection("collection_name").aggregate([
  {$match: {br_date: this.data.date}},
  {$unwind: "$loans"},
  {$unwind: "$loans"},
  {$match: {"loans.category": "rural"}},
  {$replaceRoot: {newRoot: "$loans"}}
]).toArray()

问题2:根据loan_id删除指定的贷款数据

针对嵌套数组,用$pull配合数组通配符定位并删除目标条目:

db.collection("collection_name").updateOne(
  // 匹配目标文档
  {br_date: this.data.date},
  // 从所有嵌套数组中移除loan_id匹配的元素
  {$pull: {
    "loans.$[]": {loan_id: 目标ID} // 替换为实际要删除的loan_id,比如1
  }}
)

说明:loans.$[]表示匹配外层loans数组的所有元素,$pull会自动从每个内层数组中移除符合条件的贷款。

问题3:根据loan_id更新指定的贷款数据

使用arrayFilters精准定位嵌套数组中的目标贷款并更新:

db.collection("collection_name").updateOne(
  // 匹配包含目标贷款的文档
  {
    br_date: this.data.date,
    "loans": {$elemMatch: {$elemMatch: {loan_id: 目标ID}}} // 替换为实际loan_id
  },
  // 更新目标字段
  {$set: {
    "loans.$[outer].$[inner].loan_name": "新贷款名称",
    "loans.$[outer].$[inner].category": "新分类"
  }},
  // 定义数组匹配规则
  {arrayFilters: [
    {"inner.loan_id": 目标ID}
  ]}
)

说明:arrayFilters指定内层数组的匹配条件,$[outer]和$[inner]分别定位外层、内层数组元素,实现精准更新。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 13:15:07