

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
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" } ] }
- Related Questions & Answers
- Querying an array of arrays in MongoDB?
- Querying array elements with MongoDB?
- Querying object's field array values in MongoDB?
- Querying on an array of objects for specific nested documents with MongoDB?
- Querying with MongoDB subelement?
- Querying internal array size in MongoDB?
- Increment value of an array element with array object in MongoDB
- Query on the last object of an array with MongoDB
- Remove object from array in MongoDB?
- Creating String Object from certain part of a character Array in Java
- How to get items from an object array in MongoDB?
- Querying array of Embedded Documents in MongoDB based on Range?
- MongoDB query to find data from an array inside an object?
- Increment a property value of an element in array object with MongoDB
- Querying null value in MongoDB?
Advertisements