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 for documents matching array, irrespective of elements order
For this, use $all in MongoDB. The $all operator in MongoDB selects the documents where the value of a field is an array that contains all the specified elements.
Let us first create a collection with documents −
> db.demo370.insertOne(
... {
... "Name" : "Chris",
... "details" : [
... {
... "Subject" : "MySQL",
... "CountryName" : "US"
... },
... {
... "Subject" : "MongoDB",
... "CountryName" : "UK"
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e57e9892ae06a1609a00af0")
}
> db.demo370.insertOne(
... {
... "Name" : "David",
... "details" : [
... {
"Subject" : "Java",
... "CountryName" : "AUS"
... },
... {
... "Subject" : "Spring",
... "CountryName" : "UK"
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e57e9972ae06a1609a00af1")
}
Display all documents from a collection with the help of find() method −
> db.demo370.find();
This will produce the following output −
{
"_id" : ObjectId("5e57e9892ae06a1609a00af0"), "Name" : "Chris", "details" : [
{ "Subject" : "MySQL", "CountryName" : "US" },
{ "Subject" : "MongoDB", "CountryName" : "UK" }
]
}
{
"_id" : ObjectId("5e57e9972ae06a1609a00af1"), "Name" : "David", "details" : [
{ "Subject" : "Java", "CountryName" : "AUS" },
{ "Subject" : "Spring", "CountryName" : "UK" }
]
}
Following is the query for documents matching array, irrespective of elements order −
> db.demo370.find({
... details: {$all: [
... {Subject:"MySQL","CountryName" : "US"},
... {Subject:"MongoDB", "CountryName" : "UK"}
... ]}})
This will produce the following output −
{
"_id" : ObjectId("5e57e9892ae06a1609a00af0"), "Name" : "Chris", "details" : [
{ "Subject" : "MySQL", "CountryName" : "US" },
{ "Subject" : "MongoDB", "CountryName" : "UK" }
]
} Advertisements
