Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Extract a MongoDB document with a specific string
To extract a MongoDB document with a specific string, use $match in MongoDB. Let us create a collection with documents −
> db.demo424.insert(
... {
...
... "Information" : [
... {
... id:10,
... Name:"Chris"
... },
... {
... id:11,
... Name:"David"
... }
... ]
... }
... )
WriteResult({ "nInserted" : 1 })
>
> db.demo424.insert(
... {
...
... "Information" : [
... {
... id:101,
... Name:"Mike"
... },
... {
... id:102,
... Name:"John"
... }
... ]
... }
... )
WriteResult({ "nInserted" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo424.find();
This will produce the following output −
{ "_id" : ObjectId("5e74eb9dbbc41e36cc3cae6a"), "Information" : [ { "id" : 10, "Name" : "Chris" }, { "id" : 11, "Name" : "David" } ] }
{ "_id" : ObjectId("5e74eb9ebbc41e36cc3cae6b"), "Information" : [ { "id" : 101, "Name" : "Mike" }, { "id" : 102, "Name" : "John" } ] }
Following is the query to extract a MongoDB document with a specific string −
> db.demo424.aggregate(
... [ { $match : { "Information.Name": "Chris" } } ]
... );
This will produce the following output −
{ "_id" : ObjectId("5e74eb9dbbc41e36cc3cae6a"), "Information" : [ { "id" : 10, "Name" : "Chris" }, { "id" : 11, "Name" : "David" } ] }Advertisements