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
Extract a MongoDB document with a specific string
To extract a MongoDB document with a specific string, use the $match operator in an aggregation pipeline to filter documents containing the target string value.
Syntax
db.collection.aggregate([
{ $match: { "field": "specific_string" } }
]);
Create Sample Data
db.demo424.insertMany([
{
"Information": [
{
id: 10,
Name: "Chris"
},
{
id: 11,
Name: "David"
}
]
},
{
"Information": [
{
id: 101,
Name: "Mike"
},
{
id: 102,
Name: "John"
}
]
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("..."),
ObjectId("...")
]
}
Display All Documents
db.demo424.find();
{ "_id": ObjectId("5e74eb9dbbc41e36cc3cae6a"), "Information": [ { "id": 10, "Name": "Chris" }, { "id": 11, "Name": "David" } ] }
{ "_id": ObjectId("5e74eb9ebbc41e36cc3cae6b"), "Information": [ { "id": 101, "Name": "Mike" }, { "id": 102, "Name": "John" } ] }
Extract Document with Specific String
Find documents where any element in the Information array has Name "Chris" ?
db.demo424.aggregate([
{ $match: { "Information.Name": "Chris" } }
]);
{ "_id": ObjectId("5e74eb9dbbc41e36cc3cae6a"), "Information": [ { "id": 10, "Name": "Chris" }, { "id": 11, "Name": "David" } ] }
Alternative Using find()
You can also use the simpler find() method for the same result ?
db.demo424.find({ "Information.Name": "Chris" });
Conclusion
Use $match in aggregation pipelines or find() with dot notation to extract documents containing specific string values in nested arrays. Both methods effectively filter documents based on string matching criteria.
Advertisements
