 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP 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
Querying from part of object in an array with MongoDB
To query from part of object in an array, use $findOne() and $all. Let us first create a collection with documents −
> db.demo25.insertOne( ... { ... ...    "Details":[ ...       { ...          "UserId":"Carol101", ...          "UserName":"Carol" ...       }, ...       { ...          "UserId":"David102", ...          "UserName":"David" ...       } ...    ] ... } ... ); {    "acknowledged" : true,    "insertedId" : ObjectId("5e14c86e22d07d3b95082e77") } > db.demo25.insertOne( ... { ... ...    "Details":[ ...       { ...          "UserId":"Chris101", ...          "UserName":"Chris" ...       }, ...       { ...          "UserId":"Mike102", ...          "UserName":"Mike" ...       } ...    ] ... } ... ); {    "acknowledged" : true,    "insertedId" : ObjectId("5e14c86f22d07d3b95082e78") } Display all documents from a collection with the help of find() method −
> db.demo25.find();
This will produce the following output −
{ "_id" : ObjectId("5e14c86e22d07d3b95082e77"), "Details" : [ { "UserId" : "Carol101", "UserName" : "Carol" }, { "UserId" : "David102", "UserName" : "David" } ] } { "_id" : ObjectId("5e14c86f22d07d3b95082e78"), "Details" : [ { "UserId" : "Chris101", "UserName" : "Chris" }, { "UserId" : "Mike102", "UserName" : "Mike" } ] } Here is how to query from part of object in array −
> db.demo25.findOne({ "Details.UserId":{$all : ["Carol101","David102"]}}); This will produce the following output −
{    "_id" : ObjectId("5e14c86e22d07d3b95082e77"),    "Details" : [       {          "UserId" : "Carol101",          "UserName" : "Carol"       },       {          "UserId" : "David102",          "UserName" : "David"       }    ] }Advertisements
 