首页 > 解决方案 > mongoDB 通过 id 查找并返回匹配的子文档

问题描述

我有这个收藏:

    {
     _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"}]
    }

我想像这样查询集合:find the document by user_id and return only {_.id:0, name:"john"}insidelist 找不到任何线索如何做到这一点

一些示例可以更好地解释我想要实现的目标:

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

我知道它不仅对解释我想要达到的目标有效。

标签: mongodbmongoosemongodb-query

解决方案


你可以试试这个$unwind

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

操场


推荐阅读