Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
MongoDB query with $all in array
In MongoDB, $all is used to select 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.demo163.insertOne(
... {
... "ClientDetails": [{
... "ClientName": "Chris"
...
... }, {
... "ClientName": "David"
...
... }
... ]
...
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e3686d49e4f06af551997c5")
}
> db.demo163.insertOne(
... {
... "ClientDetails": [{
... "ClientName": "Mike"
...
... }, {
... "ClientName": "Sam"
...
... }
... ]
...
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e3686d59e4f06af551997c6")
}
>
db.demo163.insertOne(
... {
... "ClientDetails": [{
... "ClientName": "Robert"
...
... }, {
... "ClientName": "Sam"
...
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e3686d59e4f06af551997c7")
}
Display all documents from a collection with the help of find() method −
> db.demo163.find();
This will produce the following output −
{ "_id" : ObjectId("5e3686d49e4f06af551997c5"), "ClientDetails" : [ { "ClientName" : "Chris" }, { "ClientName" : "David" } ] }
{ "_id" : ObjectId("5e3686d59e4f06af551997c6"), "ClientDetails" : [ { "ClientName" : "Mike" }, { "ClientName" : "Sam" } ] }
{ "_id" : ObjectId("5e3686d59e4f06af551997c7"), "ClientDetails" : [ { "ClientName" : "Robert" }, { "ClientName" : "Sam" } ] }
Following is the query for $all in MongoDB −
> db.demo163.find({"ClientDetails": {$all: [{"ClientName": "Mike"}, {"ClientName": "Sam"}]}});
This will produce the following output −
{ "_id" : ObjectId("5e3686d59e4f06af551997c6"), "ClientDetails" : [ { "ClientName" : "Mike" }, { "ClientName" : "Sam" } ] } Advertisements
