Ask Your Question
3

How can I use MongoDB to search within a sub-document that is contained within another sub-document?

asked 2023-06-07 08:49:13 +0000

pufferfish gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-06-07 08:51:02 +0000

djk gravatar image

You can use dot notation to search within a sub-document that is contained within another sub-document in MongoDB. For example, if you have a document with the following structure:

{
  "name": "John",
  "address": {
    "city": "New York",
    "zip": "10001",
    "phone": {
      "home": "123-456-7890",
      "mobile": "456-789-0123"
    }
  }
}

To search for all documents where the home phone number is "123-456-7890", you can use the following query:

db.collection.find({"address.phone.home": "123-456-7890"})

This would return all documents where the "home" phone number in the "phone" sub-document within the "address" sub-document is "123-456-7890".

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-07 08:49:13 +0000

Seen: 7 times

Last updated: Jun 07 '23