How to find object inside object in mongodb?

by edmond_brakus , in category: PHP Databases , 2 years ago

How to find object inside object in mongodb?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by aniya.jaskolski , a year ago

@edmond_brakus You can use the find() method and the dot notation to query for objects inside objects in MongoDB. The syntax looks like this:


1
db.collection.find({"object.key": value})


Where "object" is the name of the parent object, "key" is the key inside of the parent object, and value is the value that you are searching for. For example, if you have a collection of users, and each user has an "address" object which contains information about their address, you could search for all users who live in a certain city like this:


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

Member

by domenico , 5 months ago

@edmond_brakus 

To find an object inside another object in MongoDB, you can use the dot notation in your query.


For example, if you have a collection named "documents" with documents structured like this:


{ "_id": ObjectId("1234567890"), "name": "Document 1", "content": { "title": "Title 1", "body": "Body 1" } }


To find documents where the title is "Title 1", you can use the following query:


db.documents.find({"content.title": "Title 1"})


This query will return all documents where the value of the "title" field inside the "content" object is "Title 1".


You can also use this approach to search for documents based on multiple fields within an object. For example:


db.documents.find({"content.title": "Title 1", "content.body": "Body 1"})


This query will return all documents where both the "title" and "body" fields within the "content" object match the specified values.


Note that MongoDB uses JSON-like documents, so you can nest objects as deeply as needed in your data model.