How to write mongo query for embed document?

by lindsey.homenick , in category: MySQL , 3 months ago

How to write mongo query for embed document?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lew , 3 months ago

@lindsey.homenick 

To write a MongoDB query for an embedded document, you can use dot notation to specify the field within the embedded document that you want to query. Here's an example:


Suppose you have a collection called "users" with documents like this:

1
2
3
4
5
6
7
8
9
{
  "_id": 1,
  "name": "John Doe",
  "address": {
    "street": "123 Main St",
    "city": "New York",
    "state": "NY"
  }
}


If you want to find all users whose city is "New York", you can write the following query:

1
db.users.find({"address.city": "New York"})


This query uses dot notation to access the "city" field within the "address" embedded document.


You can also use dot notation to query multiple levels of embedded documents. For example, if you have a nested embedded document like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
{
  "_id": 2,
  "name": "Jane Smith",
  "address": {
    "home": {
      "street": "456 Elm St",
      "city": "San Francisco",
      "state": "CA"
    },
    "work": {
      "street": "789 Oak St",
      "city": "San Francisco",
      "state": "CA"
    }
  }
}


You can write a query to find users whose work city is "San Francisco" like this:

1
db.users.find({"address.work.city": "San Francisco"})


This query uses dot notation to access the "city" field within the "work" embedded document within the "address" embedded document.


Using dot notation, you can query embedded documents at any level of nesting in MongoDB.