Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
MongoDB query to find a value from JSON like data?
To find a value from JSON-like data in MongoDB, use the find() method along with dot notation to access nested fields within embedded documents and arrays.
Syntax
db.collection.find({"field.nestedField": "value"})
Sample Data
db.findValueFromJsonDemo.insertOne({
"UserDetails": [{
"_id": ObjectId(),
"UserName": "Carol",
"UserMessage": "Hi"
}],
"UserFriendsName": ["John", "Sam"]
});
{
"acknowledged": true,
"insertedId": ObjectId("5cdf8a4cbf3115999ed511fd")
}
Display All Documents
db.findValueFromJsonDemo.find().pretty();
{
"_id": ObjectId("5cdf8a4cbf3115999ed511fd"),
"UserDetails": [
{
"_id": ObjectId("5cdf8a4cbf3115999ed511fc"),
"UserName": "Carol",
"UserMessage": "Hi"
}
],
"UserFriendsName": [
"John",
"Sam"
]
}
Find Value in Nested Field
To find documents where UserMessage equals "Hi" within the UserDetails array ?
db.findValueFromJsonDemo.find({"UserDetails.UserMessage": "Hi"});
{
"_id": ObjectId("5cdf8a4cbf3115999ed511fd"),
"UserDetails": [
{
"_id": ObjectId("5cdf8a4cbf3115999ed511fc"),
"UserName": "Carol",
"UserMessage": "Hi"
}
],
"UserFriendsName": [
"John",
"Sam"
]
}
Key Points
- Use dot notation to access nested fields:
"parentField.childField" - MongoDB automatically searches within arrays when using dot notation
- The query returns the entire document when a match is found
Conclusion
Use dot notation with the find() method to query nested values in JSON-like MongoDB documents. This approach works seamlessly with embedded documents and arrays.
Advertisements
