简体   繁体   English

如何返回带有 Mongoose 的嵌套文档?

[英]How to return nested document with Mongoose?

If I have this collection如果我有这个收藏

[
  {
    "_id": "637cbf94b4741277c3b53c6c",
    "text": "outter",
    "username": "test1",
    "address": [
      {
        "text": "inner",
        "username": "test2",
        "_id": "637cbf94b4741277c3b53c6e"
      }
    ],
    "__v": 0
  }
]

and would like to search for the nested document by _id and return all of the nested document.并希望通过_id搜索嵌套文档并返回所有嵌套文档。 If I do如果我做

db.collection.find({
  _id: "637cbf94b4741277c3b53c6c"
},
{
  address: {
    $eq: {
      _id: "637cbf94b4741277c3b53c6e"
    }
  }
})

I get我明白了

query failed: (Location16020) Expression $eq takes exactly 2 arguments. 1 were passed in.

Playground link游乐场链接

Question问题

Can anyone see what I am doing wrong?谁能看到我做错了什么?

use $elemMatch and also you have extra unneeded brackets.使用 $elemMatch 并且您还有多余的不需要的括号。 try尝试

db.collection.find({
  _id: "637cbf94b4741277c3b53c6c",
  address: {
    $elemMatch: {
      _id: "637cbf94b4741277c3b53c6e"
    }
  }
})

Edit: if you only want to return the address add projection like this编辑:如果您只想返回地址,请像这样添加投影

db.collection.find({
  _id: "637cbf94b4741277c3b53c6c",
  address: {
    $elemMatch: {
      _id: "637cbf94b4741277c3b53c6e"
    }
  }
},
{
  _id: 0,
  address: 1
})

One option is to use find:一种选择是使用查找:

db.collection.find({},
{
  _id: 0,
  address: {
    $elemMatch: {
      _id: "637cbf94b4741277c3b53c6e"
    }
  }
})

See how it works on the playground exampleplayground 示例中查看它是如何工作的

The other option is to use aggregation pipeline:另一种选择是使用聚合管道:

db.collection.aggregate([
  {
    $match: {
      $expr: {
        $in: [
          "637cbf94b4741277c3b53c62",
          "$address._id"
        ]
      }
    }
  },
  {
    $replaceRoot: {
      newRoot: {
        $first: {
          $filter: {
            input: "$address",
            cond: {
              $eq: [
                "$$this._id",
                "637cbf94b4741277c3b53c6e"
              ]
            }
          }
        }
      }
    }
  }
])

See how it works on the playground exampleplayground 示例中查看它是如何工作的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM