如何使用Mongoose返回嵌套文档?

7dl7o3gd  于 2022-11-24  发布在  Go
关注(0)|答案(2)|浏览(199)

如果我有这个收藏

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

并且希望按_id搜索嵌套文档并返回所有嵌套文档。如果我这样做

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

我得到

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

Playground link

问题

有人能看出我做错了什么吗?

gfttwv5a

gfttwv5a1#

使用$elemMatch,而且您还有多余的不需要的括号。尝试

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

编辑:如果你只想返回地址,添加这样的投影

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

xnifntxz2#

一个选项是使用find:

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

了解它在playground example上的工作原理
另一个选项是使用聚合管道:

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

了解它在playground example上的工作原理

相关问题