【问题标题】:mongoDB Find by id and return subdocument matchedmongoDB 通过 id 查找并返回匹配的子文档
【发布时间】:2021-08-12 19:53:25
【问题描述】:

我有这个收藏:

    {
     _id:0,
     user_id: 12,
     list: [{_.id:0, name:"john"},{_.id:1, name:"hanna"}]
    },
    {
     _id:1,
     user_id: 22,
     list: [{_.id:0, name:"john"},{_.id:1, name:"hanna"}]
    }

我想这样查询集合:通过user_id查找文档 并在list 内只返回{_.id:0, name:"john"} 找不到任何线索如何做到这一点

一些例子可以更好地解释我想要达到的目标:

const johnDoc = findOne({user_id:0}).list.findOne({name:"john"})

我知道它不能仅用于解释我想要实现的目标。

【问题讨论】:

  • 如何在user_id的基础上从列表中选择用户? user_id 中有 12 和 22,但 list 数组中没有。
  • 在我想按名称查找的列表中

标签: mongodb mongoose mongodb-query


【解决方案1】:

你可以试试这个$unwind

db.collection.aggregate([
  {
    $match: {
      user_id: 12,
      "list.name": "john"
    }
  },
  {
    $unwind: "$list"
  },
  {
    $match: {
      user_id: 12,
      "list.name": "john"
    }
  },
  
])

Playground

【讨论】:

  • 您也可以在最后阶段添加“{$replaceRoot: { newRoot: "$list" } }” 以将根文档替换为嵌套文档。
【解决方案2】:

您可以在 MongoDB 4.4 的 find 投影中使用聚合运算符,

  • $filter 迭代list 的循环并通过name 属性找到匹配的用户
  • $first 从过滤结果中选择第一个元素
db.collection.find({
  user_id: 12
},
{
  list: {
    $first: {
      $filter: {
        input: "$list",
        cond: {
          $eq: [
            "$$this.name",
            "john"
          ]
        }
      }
    }
  }
})

Playground

【讨论】:

    猜你喜欢
    • 2019-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-01
    • 2021-02-25
    • 2021-09-24
    • 1970-01-01
    相关资源
    最近更新 更多