- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 where the value of a field is an array
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" ] }
- Related Articles
- Get count of array elements from a specific field in MongoDB documents?
- Find MongoDB documents where elements of an array have a specific value?
- Find documents where all elements of an array have a specific value in MongoDB?
- MongoDB query to add up the values of a specific field in documents
- MongoDB query to get only specific fields in nested array documents?
- MongoDB query to match documents that contain an array field
- MongoDB query to match documents with array values greater than a specific value
- MongoDB query to fetch a specific document rom documents with field value set using NumberInt()?
- Find MongoDB documents where all objects in array have specific value?
- MongoDB aggregation to fetch documents with specific field value?
- MongoDB query to get record beginning with specific element from an array?
- Query an array in MongoDB to fetch a specific value
- MongoDB query for documents whose array elements does not have a specific value
- How to get items with a specific value from documents using MongoDB shell?
- MongoDB query (aggregation framework) to match a specific field value

Advertisements