
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
MongoDB Query to Get Specific List of Names from Documents with Array Field
For this, use $all. The $all operator selects the documents where the value of a field is an array that contains all the specified elements. Let us create a collection with documents −
> db.demo642.insertOne( ... { ... _id:1, ... ListOfNames:["Robert","John"] ... } ... ); { "acknowledged" : true, "insertedId" : 1 } > db.demo642.insertOne( { _id:2, ListOfNames:["Robert","Chris"] } ); { "acknowledged" : true, "insertedId" : 2 }
Display all documents from a collection with the help of find() method −
> db.demo642.find();
This will produce the following output −
{ "_id" : 1, "ListOfNames" : [ "Robert", "John" ] } { "_id" : 2, "ListOfNames" : [ "Robert", "Chris" ] }
Following is the query to get specific list of names from documents where the value of a field is an array −
> db.demo642.find({ListOfNames: { ... $all: [ "Chris", "Robert" ] ... }})
This will produce the following output −
{ "_id" : 2, "ListOfNames" : [ "Robert", "Chris" ] }
Advertisements