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" } ] }
Updated on: 2020-04-03T13:52:59+05:30

284 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements