Home > Net >  How to return nested document with Mongoose?
How to return nested document with Mongoose?

Time:11-22

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. 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?

CodePudding user response:

use $elemMatch and also you have extra unneeded brackets. 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
})

CodePudding user response:

One option is to use find:

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

See how it works on the playground example

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 example

  • Related