0

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?

2 Answers 2

1

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
})
Sign up to request clarification or add additional context in comments.

5 Comments

It also returns the parent, which I an not interested in.
@SandraSchlichting edited the answer to only select address
@SandraSchlichting and by the way are you using find on purpose? are there gonna be multiple documents with certain specifications? if not you could use findOne which returns a single document
Ahh yes, I should use findOne(). Your code works perfectly. Is it possible to only return the value, and not the address key also? Like this?: pastebin.com/C6xxBwLw
This solution will not work well if the array has more than 1 item...
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.